3 回答
TA贡献1812条经验 获得超5个赞
如果您想知道是否在数组中找到该字符串,请尝试以下函数:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
正如肖恩·柴郡指出的那样,这必须是一维数组。
例:
Sub Test()
Dim arr As Variant
arr = Split("abc,def,ghi,jkl", ",")
Debug.Print IsInArray("ghi", arr)
End Sub
(以下代码根据HansUp的评论进行了更新)
如果要在数组中匹配元素的索引,请尝试以下操作:
Function IsInArray(stringToBeFound As String, arr As Variant) 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), vbTextCompare) = 0 Then
IsInArray = i
Exit For
End If
Next i
End Function
这也假设一维数组。请记住,LBound和UBound从零开始,因此索引为2表示第三个元素,而不是第二个。
例:
Sub Test()
Dim arr As Variant
arr = Split("abc,def,ghi,jkl", ",")
Debug.Print (IsInArray("ghi", arr) > -1)
End Sub
如果您有特定的示例,请使用它来更新您的问题,否则示例代码可能不适用于您的情况。
TA贡献1871条经验 获得超13个赞
另一种选择是使用字典而不是数组:
Dim oNames As Object
Set oNames = CreateObject("Scripting.Dictionary")
'You could if need be create this automatically from an existing Array
'The 1 is just a dummy value, we just want the names as keys
oNames.Add "JOHN", 1
oNames.Add "BOB", 1
oNames.Add "JAMES", 1
oNames.Add "PHILIP", 1
这样一来,您就可以
oNames.Exists("JOHN")
字典提供的优势是与的部分匹配相比,精确匹配Filter。假设您有一个数组中的原始名称列表,但正在查找“ JO”或“ PHIL”,除了我们最初使用的四个人以外,他们实际上是两个新人。在这种情况下,Filter(oNAMES, "JO")将匹配可能不需要的“ JOHN” 。有了字典,它就不会。
TA贡献1943条经验 获得超7个赞
更简单的功能在Apple OS上也可以使用:
Function isInArray(ByVal stringToBeFound As String, ByVal arr As Variant) As Boolean
Dim element
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
添加回答
举报