如何确定对象是否是VBA中集合的成员?
具体来说,我需要找出表定义是否是TableDefs
集合的成员.
不够好吗?
Public Function Contains(col As Collection, key As Variant) As Boolean Dim obj As Variant On Error GoTo err Contains = True obj = col(key) Exit Function err: Contains = False End Function
不完全优雅,但我能找到的最好(也是最快)的解决方案是使用OnError.对于任何中型到大型集合,这将明显快于迭代.
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
您最好的选择是迭代集合的成员,看看是否匹配您正在寻找的东西.相信我,我必须多次这样做.
第二个解决方案(更糟糕的是)捕获"Item not in collection"错误,然后设置一个标志,表示该项目不存在.
这是一个老问题.我仔细阅读了所有答案和评论,测试了性能解决方案.
我想出了我的环境中最快的选项,当集合包含对象和基元时,它不会失败.
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
此外,该解决方案不依赖于硬编码的错误值.因此参数col As Collection
可以被其他一些集合类型变量替换,并且该函数仍然可以工作.例如,在我目前的项目中,我会将其作为col As ListColumns
.