gpt4 book ai didi

vba - 升级 VBA 6->7 导致错误 : If Exists in Collection

转载 作者:行者123 更新时间:2023-12-02 10:52:52 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com