VBA6代码(Excel)效果很好。升级到Office 2010 / VBA7,代码中断。
使用SO中的代码:
Determining whether an object is a member of a collection in VBA
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
我得到运行时错误5:无效的过程调用或参数。
这对我来说没有意义,因为错误发生在obj = col(key)
行上,应该由On Error GoTo err
语句覆盖,但它会停止。
其他如果X存在于集合中类型解决方案存在同样的问题。
而不是修复损坏的代码,我真正需要的是能够看到是否已经为集合设置了记录,如果可以在VBA7中以其他(新)方式完成,则可以解决问题好吧(我可以做梦)。
答案 0 :(得分:2)
我发现如果我更改指定一个对象,例如一个精简表,它就可以工作:
Public Function Contains(col As Collection, key As Variant) As Boolean
Dim ws As Excel.Worksheet
On Error GoTo err
Contains = True
Set ws = col(key)
Exit Function
err:
Contains = False
End Function
我称之为:
Sub test()
Dim ws As Excel.Worksheet
Dim coll As Collection
Set coll = New Collection
For Each ws In ThisWorkbook.Worksheets
coll.Add ws, ws.Name
Next ws
Debug.Print Contains(coll, ActiveSheet.Name)
Debug.Print Contains(coll, "not a worksheet name")
End Sub
第一次调用时为True,第二次调用为False。