vba 通过vba字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9401378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:37:54  来源:igfitidea点击:

Pass vba Dictionary

excelvba

提问by bsr

New to vba. How to pass dictionary object to another function.

vba 新手。如何将字典对象传递给另一个函数。

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

gives a compile error: User defined type not defined

给出编译错误:未定义用户定义的类型



Also,

还,

Set dict = CreateObject("Scripting.Dictionary")

works, but

有效,但是

Dim dict As New Scripting.Dictionary 

gives, "User defined type not defined"

给出,“未定义用户定义的类型”

I use excel 2010

我使用 excel 2010

回答by mwolfe02

When you use CreateObjectyou are binding the object at run-time (ie, late binding). When you use As Scripting.Dictionarythe object is bound at compile-time (ie, early binding).

当您使用时,CreateObject您是在运行时绑定对象(即后期绑定)。当你使用As Scripting.Dictionary对象是在编译时绑定(即早期绑定)。

If you want to do early binding you will need to set a reference to the correct library. To do this, go to Tools --> References... and select "Microsoft Scripting Runtime"

如果要进行早期绑定,则需要设置对正确库的引用。为此,请转至工具 --> 参考...并选择“Microsoft Scripting Runtime”

回答by mechanical_meat

To avoid the error add the Microsoft Scripting Runtime (in Tools -> References).
Simplified example:

为避免该错误,请添加 Microsoft Scripting Runtime(在工具 -> 参考中)。
简化示例:

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

回答by mrbillbenson

I would revise this answer to use late binding only, and use an object parameter:

我将修改此答案以仅使用后期绑定,并使用对象参数:

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

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

回答by GTG

You need to add a reference to the Microsoft Scripting Runtime library for your macro to be able to recognize the types. Goto Tools->References and check for Microsoft Scripting Runtime.

您需要添加对 Microsoft Scripting Runtime 库的引用,以便您的宏能够识别类型。转到工具-> 参考并检查 Microsoft Scripting Runtime。

回答by daniele3004

After you adding the "Tools->References->Microsoft Scripting Runtime" try this

添加“工具->参考->Microsoft Scripting Runtime”后,试试这个

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