我正在运行For循环以在变量数组中查找字符串。我正在使用StrComp来比较字符串。我使用的数组格式如下。
我尝试了两种方法,我将在后面描述。
当我使用col = 0时,第一种方法返回下标超出范围
Function IsInArray(stringToBeFound As String, arr As Variant, col As Integer) As Long
Dim i As Long
' default return value if value not found in array
IsInArray = -1
For i = LBound(arr) To UBound(arr)
If StrComp(stringToBeFound, arr(i, col), vbTextCompare) = 0 Then
IsInArray = i
Exit For
End If
Next i
End Function
第二种方法告诉我StrComp的类型不匹配
Function IsIn1DArray(stringToBeFound As String, arr As Variant) As Long
Dim i As Long
' default return value if value not found in array
IsIn1DArray = -1
For i = LBound(arr) To UBound(arr)
If StrComp(stringToBeFound, arr(i)) = 0 Then
IsIn1DArray = i
Exit For
End If
Next i
End Function
我过去一直在使用IsInArray和IsIn1DArray并且可以使用但不适用于这种情况。想象一下,我想搜索字符串“[TestHeader]”并返回其索引。你会怎么做?
答案 0 :(得分:1)
arr
是一个数组数组,因此您需要:
If StrComp(stringToBeFound, arr(i)(col), vbTextCompare) = 0 Then
请注意,由于子数组的大小不同,某些值可能会失败,因此您应首先测试子数组的Ubound
。
答案 1 :(得分:0)
Function IsIn1dArray(stringToBeFound As String, arr As Variant) As Long
IsIn1dArray = Application.WorksheetFunction.Match(stringToBeFound, arr, 0)
End Function