Determining whether an object is a member of a collection in VBA

前端 未结 15 1741
自闭症患者
自闭症患者 2020-11-27 05:35

How do I determine whether an object is a member of a collection in VBA?

Specifically, I need to find out whether a table definition is a member of the TableDe

相关标签:
15条回答
  • 2020-11-27 06:17

    This is an old question. I have carefully reviewed all the answers and comments, tested the solutions for performance.

    I came up with the fastest option for my environment which does not fail when a collection has objects as well as primitives.

    Public Function ExistsInCollection(col As Collection, key As Variant) As Boolean
        On Error GoTo err
        ExistsInCollection = True
        IsObject(col.item(key))
        Exit Function
    err:
        ExistsInCollection = False
    End Function
    

    In addition, this solution does not depend on hard-coded error values. So the parameter col As Collection can be substituted by some other collection type variable, and the function must still work. E.g., on my current project, I will have it as col As ListColumns.

    0 讨论(0)
  • 2020-11-27 06:18

    Your best bet is to iterate over the members of the collection and see if any match what you are looking for. Trust me I have had to do this many times.

    The second solution (which is much worse) is to catch the "Item not in collection" error and then set a flag to say the item does not exist.

    0 讨论(0)
  • 2020-11-27 06:18

    I have some edit, best working for collections:

    Public Function Contains(col As collection, key As Variant) As Boolean
        Dim obj As Object
        On Error GoTo err
        Contains = True
        Set obj = col.Item(key)
        Exit Function
        
    err:
        Contains = False
    End Function

    0 讨论(0)
提交回复
热议问题