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

时间:2015-04-10 15:03:52

标签: excel-vba variables if-statement vba excel

我有以下功能:

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等等。

2 个答案:

答案 0 :(得分:1)

如果你想制作"幻数" 2 变成一个变量,然后你会用一个数组项来代替 2

但是,如果你想要单独的逻辑,那么您使用选择案例结构。

答案 1 :(得分:1)

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

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应根据您要使用的测试进行定义,这种方法允许您定义多个运算符数组(一个数组用于+之类的运算符,{ {1}}等,另一个用于-3等值。)

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

Application.Evaluate()
相关问题