Generic way to check if a key is in a Collection in Excel VBA

后端 未结 5 1587
天涯浪人
天涯浪人 2021-01-02 00:42

I have different Collections in my code. Some hold Objects (of various kinds), others have types (like Long) within them.

Is there a way to check if a key is contain

5条回答
  •  太阳男子
    2021-01-02 01:30

    The method from Robin will fail if the Collection contains objects rather than primitive types because they need to be assigned using Set and otherwise generate an error that will result in the method returning False. Here is a small adjustment:

    'Test if a key is available in a collection
    Public Function HasKey(coll As Collection, strKey As String) As Boolean
        On Error GoTo IsMissingError
            Dim val As Variant
    '        val = coll(strKey)
            HasKey = IsObject(coll(strKey))
            HasKey = True
            On Error GoTo 0
            Exit Function
    IsMissingError:
            HasKey = False
            On Error GoTo 0
    End Function
    

提交回复
热议问题