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

前端 未结 15 1832
自闭症患者
自闭症患者 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-27 05:57

    Not exactly elegant, but the best (and quickest) solution i could find was using OnError. This will be significantly faster than iteration for any medium to large collection.

    Public Function InCollection(col As Collection, key As String) As Boolean
      Dim var As Variant
      Dim errNumber As Long
    
      InCollection = False
      Set var = Nothing
    
      Err.Clear
      On Error Resume Next
        var = col.Item(key)
        errNumber = CLng(Err.Number)
      On Error GoTo 0
    
      '5 is not in, 0 and 438 represent incollection
      If errNumber = 5 Then ' it is 5 if not in collection
        InCollection = False
      Else
        InCollection = True
      End If
    
    End Function
    

提交回复
热议问题