vba:我如何搜索集合?

l--*_*''' 3 collections vba

我正在寻找一个集合中的特定元素.我怎么知道它是否存在于集合中?

GSe*_*erg 7

如果在将项添加到集合时使用了密钥,请查看引用此密钥是否给出错误:

on error goto no_item
col.Item "key"
msgbox "Item exists"

exit sub

no_item:    
msgbox "Item does not exist"
Run Code Online (Sandbox Code Playgroud)

否则你必须遍历所有项目,看看是否有你需要的项目.


sha*_*esh 7

集合是基于索引的.因此,您必须遍历集合才能搜索项目.

Sub test()
Dim iCtr As Integer
Dim itemCount As Integer

Dim myData As Collection
Set myData = New Collection

Dim searchFor As String

myData.Add "MS", "11"
myData.Add "Oracle", "22"
myData.Add "Google", "33"

'** Searching based on value
searchFor = "Google"

itemCount = myData.Count
For iCtr = 1 To itemCount
    If myData(iCtr) = searchFor Then
        MsgBox myData(iCtr)
        Exit For
    End If
Next

'** Searching by key
MsgBox myData.Item("22")
End Sub
Run Code Online (Sandbox Code Playgroud)


sch*_*jos 5

我使用一个简单的工具函数来遍历一个集合。它没有直接访问索引,它使用了应该使用的 VBA 语言功能(变体和每个-Loop 的比较)。

Public Function ExistsIn(item As Variant, lots As Collection) As Boolean
    Dim e As Variant
    ExistsIn = False
    For Each e In lots
        If item = e Then
            ExistsIn = True
            Exit For
        End If
    Next
End Function
Run Code Online (Sandbox Code Playgroud)