升级VBA 6-> 7会导致错误:如果存在于收集中

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中以其他(新)方式完成,那也可以解决问题(我可以梦想).

最佳答案 我发现,如果我更改指定一个对象,例如一个精简表,它的工作原理是:

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.

点赞