作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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。
关于vba - 升级 VBA 6->7 导致错误 : If Exists in Collection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16243207/
我是一名优秀的程序员,十分优秀!