在VBA中搜索数组中的字符串是否容易(单行)?或者我是否需要遍历每个元素并将其与目标字符串进行比较?
编辑: 它是一维数组。我只需要知道 IF 字符串就在数组中的某个位置。
IE:
names(JOHN, BOB, JAMES, PHLLIP)
如何判断阵列中是否有“JOHN”,它需要最小化,因为它将重复约5000次,我不希望该功能减慢整个过程。
答案 0 :(得分:58)
如果您想知道字符串是否在数组中找到,请尝试以下函数:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function
如Sean Cheshire所指出,这必须是一维数组。
示例:强>
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
这也假定为1-D阵列。请记住LBound和UBound是从零开始的,因此索引2表示第三个元素,而不是第二个元素。
示例:强>
Sub Test()
Dim arr As Variant
arr = Split("abc,def,ghi,jkl", ",")
Debug.Print (IsInArray("ghi", arr) > -1)
End Sub
如果您有特定的示例,请使用它更新您的问题,否则示例代码可能不适用于您的情况。
答案 1 :(得分:22)
另一种选择是使用字典而不是数组:
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"哪个可能不合需要。凭借字典,它赢了。
答案 2 :(得分:13)
强制完全匹配(即没有部分匹配)的另一个选项是:
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
您可以在此处阅读有关Match方法及其参数的更多信息 http://msdn.microsoft.com/en-us/library/office/ff835873(v=office.15).aspx
答案 3 :(得分:5)
更简单的功能也适用于Apple OS:
Function isInArray(ByVal stringToBeFound As String, ByVal arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
答案 4 :(得分:4)
有一个函数会返回找到的所有字符串的数组。
Filter(sourcearray, match[, include[, compare]])
源阵列必须是1维的
该函数将返回数组中包含match
字符串的所有字符串
答案 5 :(得分:3)
这是另一个答案。它工作快速,可靠(参见atomicules'答案)并具有紧凑的调用代码:
' Returns true if item is in the array; false otherwise.
Function IsInArray(ar, item$) As Boolean
Dim delimiter$, list$
' Chr(7) is the ASCII 'Bell' Character.
' It was chosen for being unlikely to be found in a normal array.
delimiter = Chr(7)
' Create a list string containing all the items in the array separated by the delimiter.
list = delimiter & Join(ar, delimiter) & delimiter
IsInArray = InStr(list, delimiter & item & delimiter) > 0
End Function
样本使用:
Sub test()
Debug.Print "Is 'A' in the list?", IsInArray(Split("A,B", ","), "A")
End Sub
答案 6 :(得分:2)
这是我的代码,灵感来自@atomicules
Public Function IsName(name As String) As Boolean
Dim names As Object
Set names = CreateObject("System.Collections.ArrayList")
names.Add "JOHN"
names.Add "BOB"
names.Add "JAMES"
names.Add "PHLLIP"
IsName = names.Contains(name)
End Function
这是用法:
If IsName("JOHN") Then ...
答案 7 :(得分:1)
如果它是常量列表,那么您可以按如下方式使用Select Case:
Dim Item$: Item = "A"
Select Case Item
Case "A", "B", "C"
' If 'Item' is in the list then do something.
Case Else
' Otherwise do something else.
End Select
答案 8 :(得分:1)
Case
语句可能更简单地适合某些应用程序:
select case var
case "a string", "another string", sVar
'do something
case else
'do something else
end select
答案 9 :(得分:0)
您可以在不使用包装函数的情况下使用以下内容,但它提供了更好的API:
Function IsInArray(ByVal findString as String, ByVal arrayToSearch as Variant) as Boolean
IsInArray = UBound(Filter(arrayToSearch,findString)) >= 0
End Function
Filter
函数具有以下签名:
Filter(sourceArray, stringToMatch, [Include As Boolean = True], [Compare as VbCompareMethod = vbBinaryCompare])
答案 10 :(得分:0)
完成对 Jimmy Pena 已接受答案的评论
<块引用>正如 SeanC 指出的,这必须是一维数组。
以下示例调用演示了对于 1-dim 数组,不能仅调用 IsInArray()
函数,
但也对于“平面”二维数组:
Sub TestIsInArray()
Const SearchItem As String = "ghi"
Debug.Print "SearchItem = '" & SearchItem & "'"
'----
'a) Test 1-dim array
Dim Arr As Variant
Arr = Split("abc,def,ghi,jkl", ",")
Debug.Print "a) 1-dim array " & vbNewLine & " " & Join(Arr, "|") & " ~~> " & IsInArray(SearchItem, Arr)
'----
'//quick tool to create a 2-dim 1-based array
Dim v As Variant, vals As Variant
v = Array(Array("abc", "def", "dummy", "jkl", 5), _
Array("mno", "pqr", "stu", "ghi", "vwx"))
v = Application.Index(v, 0, 0) ' create 2-dim array (2 rows, 5 cols)
'b) Test "flat" 2-dim arrays
Debug.Print "b) ""flat"" 2-dim arrays "
Dim i As Long
For i = LBound(v) To UBound(v)
'slice "flat" 2-dim arrays of one row each
vals = Application.Index(v, i, 0)
'check for findings
Debug.Print Format(i, " 0"), Join(vals, "|") & " ~~> " & IsInArray(SearchItem, vals)
Next i
End Sub
Function IsInArray(stringToBeFound As String, Arr As Variant) As Boolean
'Site: https://stackoverflow.com/questions/10951687/how-to-search-for-string-in-an-array/10952705
'Note: needs a "flat" array, not necessarily a 1-dimensioned array
IsInArray = (UBound(Filter(Arr, stringToBeFound)) > -1)
End Function
VB 编辑器的即时窗口中的结果
SearchItem = 'ghi'
a) 1-dim array
abc|def|ghi|jkl ~~> Wahr
b) "flat" 2-dim arrays
1 abc|def|dummy|jkl|5 False
2 mno|pqr|stu|ghi|vwx True