VBA从函数返回字典

时间:2019-07-12 10:54:31

标签: excel vba function dictionary object

问题:我想创建一个获取一个字符串并返回字典的函数。 经过大量阅读,我准确地再现了一些问题中给出的代码,最终得到了一个看起来可行的解决方案。但是有些事情我不理解。

此处的代码有点长,因为其中包含一些注释:

Private Sub testdictionary()
Dim dict_in_sub As Scripting.Dictionary
    ' Do I really need this??:
    'Set dict_in_sub = New Scripting.Dictionary
    ' or this:
    'Set dict_in_sub =CreateObject("Scripting.Dictionary")

Call returning_dict_func("word1.word2")
Set dict_in_sub = returning_dict_func("whatever.second")

MsgBox "in code:" & Chr(10) & dict_in_sub("A") & Chr(10) & dict_in_sub("B")
End Sub

此函数称为:

Function returning_dict_func(SC As String) As  Scripting.Dictionary
' should this function return a dictionary or an object or a scrippting dictionary??

Dim dictionary_in_function
    Set dictionary_in_function = CreateObject("Scripting.Dictionary")

'take the first and second part of the string separated by the period
dictionary_in_function("A") = Mid(SC, 1, InStr(SC, ".") - 1)
dictionary_in_function("B") = Mid(SC, InStr(SC, ".") + 1, Len(SC))

MsgBox dictionary_in_function("A") & Chr(10) & dictionary_in_function("B")
Set returning_dict_func = dictionary_in_function
End Function

即使我运行了代码,也有一些事情使从VBA中的函数返回字典变得很奇怪 在代码中引入以下更改使其不起作用:

Dim dict_in_sub as Dictionary
' it does not work. What is the difference between dictionary and scrippting.dictionary?

' defining the function as returning a dictionary does not work
Function returning_dict_func(SC As String) As Dictionary

' if both are dictionaries it does not work
 Dim dict_in_sub as Dictionary
 Function returning_dict_func(SC As String) As Dictionary

为什么字典与scripting.dictionary不同?

何时应使用

初始化

设置dict_modifiers = CreateObject(“ Scripting.Dictionary”)

谢谢

注意: 我看了一下: a)Excel 2010中的VBA:Scripting.Dictionary函数的返回值不会作为参数传递给包装函数调用 b)从vba中的函数返回字典。错误450 c)从VBA中的函数返回字典对象

1 个答案:

答案 0 :(得分:1)

CreateObjectNew之间的区别在于,您需要为对象(New)引用一个带有对象(Microsoft Scripting Runtime)的库,而您不需要可以使用CreateObject引用任何内容。

使用后一种定义时,由于类型已声明并已知,因此您还可以具有一些智能提示。

您可以在其他答案中找到更多信息:What are the differences between using the New keyword and calling CreateObject in Excel VBA?

对于Dictionary对象,Scripting.Dictionary是正确的类型。在https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dictionary-object中进一步了解它。

顺便说一句,在VBA中,当值是一个对象(通常不同于数字,字符串或日期)时,必须使用Set分配变量值。