从vba中的函数返回字典。错误450

时间:2017-11-23 15:18:23

标签: vba excel-vba dictionary excel

我编写了一个创建字典并面临奇怪行为的函数:我只能在函数内部通过键检索值。当我尝试使用函数返回的字典时,我收到Run-time error '450' 我的代码是:

Option Explicit
Function year_range_dict() As Object
    Dim d
    Set d = CreateObject("Scripting.Dictionary")
    d.Add "a", "aaa"
    d.Add "b", "bbb"
    d.Add "c", "ccc"
    If d.Exists("c") Then
        MsgBox d("c")
        End If
    Set year_range_dict = d
End Function
Sub DefaultRates()
    MsgBox year_range_dict()("a"), "outside of function"
End Sub

运行此代码时,我会收到消息框,其中包含" CCC"然后是错误消息

2 个答案:

答案 0 :(得分:2)

我很抱歉这种愚蠢:我忘了一件事:套装。这是工作代码:

Option Explicit
Function year_range_dict() As Object
    Dim d
    Set d = CreateObject("Scripting.Dictionary")
    d.Add "a", "aaa"
    d.Add "b", "bbb"
    d.Add "c", "ccc"
    If d.Exists("c") Then
        MsgBox d("c")
        End If
    Set year_range_dict = d
End Function
Sub DefaultRates()
    Dim d
    Set d=year_range_dict()
    MsgBox d("a")
End Sub

答案 1 :(得分:0)

瞧:

Function year_range_dict() As Object

    Dim d

    Set d = CreateObject("Scripting.Dictionary")
    d.Add "a", "aaa"
    d.Add "b", "bbb"
    d.Add "c", "ccc"
    If d.Exists("c") Then
        MsgBox d("c")
    End If
    Set year_range_dict = d

End Function

Sub DefaultRates()

    MsgBox year_range_dict()("a")

End Sub

问题在于您提供了额外的参数"outside of function"。不知道你试图用它做什么,但year_range_dict()("a")返回键"a"的字典值。

如果“功能之外”的想法是它应该是MsgBox的标题,那么它应该是这样的:MsgBox year_range_dict()("a"), Title:="outside of function"

Ctrl + I 查看MsgBox的参数:

enter image description here