`if` 语句的逻辑测试可以是 excel vba 中的变量吗?

Can a logic test for an `if` statement be a variable in excel vba?

我有以下功能:

Function get_equal_array_subset(column_label As String, _
                                                loop_array() As Variant, _
                                                values_array() As Variant)
    ' this function outputs an array of value from the values_array, based on a loop through the loop_array
    ' column_label is the first item in the array of the ouput array; i.e. the column lable of a new range
    ' loop_array is array being looped through and testing each value
    ' valus_array is the array from which values are taken with the test is met in the first array
    ' *** arrays have to be of equal lenght ***


    Dim subset_array() As Variant
    subset_array = Array(column_label)

    Dim rows_dim As Long
    Dim cols_dim As Integer

    Dim agent_subset_counter As Long
    agent_subset_counter = 0 ' counter to set the key for the new array

    For rows_dim = 2 To UBound(loop_array, 1)
        For cols_dim = 1 To UBound(loop_array, 2)

                If loop_array(rows_dim, cols_dim) > 2 Then
                        agent_subset_counter = agent_subset_counter + 1 '  increase the subset counter by 1
                        ReDim Preserve subset_array(agent_subset_counter) ' resize the array account for the next id
                        subset_array(agent_subset_counter) = values_array(rows_dim, cols_dim) ' add the new id to the agent subset
                End If
        Next cols_dim
    Next rows_dim
    get_equal_array_subset = subset_array
End Function

有没有办法让 If loop_array(rows_dim, cols_dim) > 2 Then 成为一个变量?假设我希望测试是 > 3= 5non blank...等

如果您想将 "magic number" 2 变成一个变量,那么您可以使用数组项代替 2.

但是,如果您想要单独的逻辑,那么您可以使用 Select Case 结构。

我会选择 Application class 的神奇 Application.Evaluate() 方法。一个例子可能是将一系列测试定义到一个数组中,比方说:

Dim myTests(4)
myTests(1) = "> 3"
myTests(2) = "= 5"
myTests(3) = "+3 < 5"
myTests(4) = "- 4 + sum(1,2) < 5" 

因此,使用简单的语句:

If Application.Evaluate(loop_array(rows_dim, cols_dim) & myTests(j)) Then

显然,变量 j 应该根据您要使用的测试来定义,这种方法将允许您定义多个运算符数组(一个数组用于像 + 这样的运算符, - 等,另一个用于 35 等值)

注意 如果您还不知道,Application.Evaluate() 方法将计算表达式并像 Excel 那样返回结果。它基本上使用 Excel 用于评估您在单元格中写入的内容的相同代码:

Application.Evaluate("2+3") --> 5
Application.Evaluate("2 < 3") --> True
Application.Evaluate("IF(2=3,1,2)") --> 2
'etc.