在vba动态表中查找值

时间:2014-04-22 16:15:17

标签: vba excel-vba excel

我有一个动态的字符串表,我在vba中定义了(我确切地说它不是XL表),我想检查这个表中是否存在特定的值。这是我职能的一部分:

Dim tableOfSizes() As String
sizeTable(0)=size1
sizeTable(1)=size2
sizeTable(2)=size3
'size2 and size3 are optional parameters of the function

If instr(tableOfSizes, "Medium") <> 0 Then
' Action if "Medium" is found in the table
End If

但似乎instr不适用于表,或者至少不适用于动态表。这是问题吗?

1 个答案:

答案 0 :(得分:1)

对于 1D-array ,您可以使用以下方法。

方式№1 Filter function

If UBound(Filter(tableOfSizes, "Medium")) <> -1 Then
    ' Action if "Medium" is found in the table
End If

方式№2( for Excel-VBA Application.Match

If Not IsError(Application.Match("Medium", tableOfSizes, 0)) Then
    ' Action if "Medium" is found in the table
End If

对于多维度数组,您可以使用以下函数:

Function contains(arr, elem) As Boolean
    Dim a
    contains = False
    For Each a In arr
        If a = elem Then
            contains = True
            Exit Function
        End If
    Next
End Function

然后:

If contains(tableOfSizes, "Medium") Then
    ' Action if "Medium" is found in the table
End If