确定集合中是否存在密钥或项目

按键

Scripting.Dictionary 不同,Collection 没有用于确定给定键是否存在的方法或者用于检索 Collection 中存在的键的方法。确定密钥是否存在的唯一方法是使用错误处理程序:

Public Function KeyExistsInCollection(ByVal key As String, _
                                      ByRef container As Collection) As Boolean
    With Err
        If container Is Nothing Then .Raise 91
        On Error Resume Next
        Dim temp As Variant
        temp = container.Item(key)
        On Error GoTo 0

        If .Number = 0 Then
            KeyExistsInCollection = True 
        ElseIf .Number <> 5 Then
            .Raise .Number
        End If
    End With
End Function

项目

确定项目是否包含在 Collection 中的唯一方法是迭代 Collection 直到项目被定位。请注意,因为 Collection 可以包含基元或对象,所以需要一些额外的处理来避免比较期间的运行时错误:

Public Function ItemExistsInCollection(ByRef target As Variant, _
                                       ByRef container As Collection) As Boolean
    Dim candidate As Variant
    Dim found As Boolean
    
    For Each candidate In container
        Select Case True
            Case IsObject(candidate) And IsObject(target)
                found = candidate Is target
            Case IsObject(candidate), IsObject(target)
                found = False
            Case Else
                found = (candidate = target)
        End Select
        If found Then
            ItemExistsInCollection = True
            Exit Function
        End If
    Next
End Function