確定集合中是否存在金鑰或專案

按鍵

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