VBA 查找数组(由范围组成)是否包含特定值

VBA Find if an array (made up of range) contains a specific value

我正在尝试编写一个代码,该代码采用特定的预定义硬编码值和由从第 3 列到最后一列的值(只有一行)的值组成的范围,并查看我的数组是否包含该特定项目。我的代码:

Dim LastColumn As Long
LastColumn = Cells(Cells.Find("Parameters", lookat:=xlWhole).Row, Columns.Count).End(xlToLeft).Column

Dim Environment
Environment = ThisWorkbook.Worksheets("Specification").Range(Cells(Cells.Find("Environment").Row, 3), Cells(Cells.Find("Environment").Row, LastColumn)).Value

If ItemIsInArray(Environment , "SKIN") Then
'do stuff
End if

和函数

Function ItemIsInArray(arr As Variant, arrX As Variant) As Boolean
   
'Declare variables
Dim i As Long, j As Long, boolFound As Boolean, mtch

'Main function
If Not IsArray(arrX) Then
    For j = LBound(arr) To UBound(arr)
        If CStr(arr(j)) = CStr(arrX) Then ItemIsInArray = True: Exit For
    Next j
    Exit Function
End If
   
For i = LBound(arrX) To UBound(arrX, 2)
    For j = LBound(arr) To UBound(arr)
        If CStr(arr(j)) = CStr(arrX(1, i)) Then
            boolFound = True: Exit For
        End If
    Next j
        
If boolFound Then ItemIsInArray = True: Exit Function
    boolFound = False
Next i

ItemIsInArray = False

End Function

问题是returns“下标超出范围” “If CStr(arr(j)) = CStr(arrX) Then ItemIsInArray = True: Exit For”中的“CStr(arr(j))”。

我想问题是我如何将范围转换为数组的方式,但我似乎无法弄清楚。有人可以帮我解决这个问题吗?

您的数组是二维的,您只在索引器中传递一个维度:arr(j)

您需要遍历两个维度并使用 LBound(array, dimension)UBound(array, dimension) 重载。

类似于以下内容:

For i = LBound(arr, 1) To UBound(arr, 1)
    For j = LBound(arr, 2) To UBound(arr, 2)
        If CStr(arr(i, j)) = CStr(arrX) Then ItemIsInArray = True: Exit For
    Next j
Next i