2016-04-20 57 views
0

我正在運行For循環來查找變體數組中的字符串。我正在使用StrComp來比較字符串。我正在使用以下格式的數組。 enter image description hereVBA - StrComp類型不匹配或下標超出範圍

我已經嘗試了兩種方法,我將在下文中描述。

1方法返回下標超出範圍,當我使用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

不起作用。該字符串不是來自一個單元格... – peetman

回答

1

arr是一個數組的數組,所以你需要:

If StrComp(stringToBeFound, arr(i)(col), vbTextCompare) = 0 Then 

注意這可能會失敗的一些值作爲你的子數組大小也不一樣,所以你應該測試的Ubound首先是子陣列。

+0

感謝它做到了! – peetman

0
Function IsIn1dArray(stringToBeFound As String, arr As Variant) As Long 

    IsIn1dArray = Application.WorksheetFunction.Match(stringToBeFound, arr, 0) 

End Function