excel 如何在VBA中将字典作为参数传递?

bvhaajcl  于 2023-06-07  发布在  其他
关注(0)|答案(5)|浏览(531)

如何将字典对象传递给另一个函数?代码如下:

Sub aaa(dict As Object)
Set dict = CreateObject("Scripting.Dictionary")
...
process dict 
End Sub

Sub process(dict As Scripting.Dictionary)
    MsgBox dict.Count
End Sub

给出编译错误“User defined type not defined”。
还有

Set dict = CreateObject("Scripting.Dictionary")

工作,但是

Dim dict As New Scripting.Dictionary

给出“未定义的用户定义类型”。
我用的是Excel 2010。

gcuhipw9

gcuhipw91#

当你使用CreateObject时,你是在运行时绑定对象(即后期绑定)。当使用As Scripting.Dictionary时,对象在编译时绑定(即早期绑定)。
如果你想做早期绑定,你需要设置一个对正确库的引用。要执行此操作,请转到“工具”-->“引用”...然后选择“Microsoft Scripting Runtime”

vmpqdwk3

vmpqdwk32#

为了避免这个错误,请添加Microsoft Scripting Runtime(在Tools -> References中)。
简化示例:

Sub test_dict()
    Dim dict As New Scripting.Dictionary
    Call process(dict)
End Sub

Sub process_dict(dict As Scripting.Dictionary)
    MsgBox dict.Count
End Sub
uqdfh47h

uqdfh47h3#

我会修改这个答案,只使用后期绑定,并使用一个对象参数:

Sub aaa(dict As Object)
Set dict = CreateObject("Scripting.Dictionary")
...
process dict 
End Sub

Sub process(dict As Object)
    MsgBox dict.Count
End Sub
mrfwxfqh

mrfwxfqh4#

您需要添加对Microsoft脚本运行时库的引用,以便宏能够识别类型。后藤Tools->References并检查Microsoft Scripting Runtime。

d4so4syb

d4so4syb5#

在添加“工具->引用->Microsoft脚本运行时”之后,尝试以下操作

Private Sub CommandButton1_Click()

    Dim myLocalDictionary As New Dictionary
    myLocalDictionary.Add "a", "aaa"
    myLocalDictionary.Add "b", "bbb"
    myLocalDictionary.Add "c", "ccc"

    Call testPassDictionary(myLocalDictionary)

End Sub

Sub testPassDictionary(myDictionary As Dictionary)
    MsgBox myDictionary.Count
End Sub

相关问题