VBA字典运行异常

VBA字典运行异常,vba,excel,dictionary,Vba,Excel,Dictionary,我在理解下面代码段的输出时遇到了很多困难 Sub TestDictionary Dim d as dictionary set d = new dictionary debug.print d.count debug.print d(1) debug.print d.count End Sub 上面的代码片段给出了如下的o/p 0 `I presume this line being the empty string 1 我

我在理解下面代码段的输出时遇到了很多困难

Sub TestDictionary
    Dim d as dictionary
    set d = new dictionary

    debug.print d.count
    debug.print d(1)
    debug.print d.count

End Sub
上面的代码片段给出了如下的o/p

0
            `I presume this line being the empty string
1
我希望debug.print d(1)行的下标超出范围,但令我恐惧的是,它返回了一个空字符串


有人能告诉我为什么会这样吗?

这是正确的行为。
Scripting.Dictionary
对象的创建方式是
dict(x)=something
分配给现有条目,如果没有,则创建条目

同时,如果没有条目存在,则读取
dict(x)
将创建带有
空变量的条目

这就是
Scripting.Dictionary
的指定方式,这种行为在许多情况下都很有用

请注意,您可以在代码中更改此行为,只需在访问条目之前检查条目是否存在:

If dict.exists(x) then
    do something with dict(x)...
End If
因此,上面的代码可以这样编写:

Sub TestDictionary
    Dim d as dictionary
    set d = new dictionary

    debug.print d.count
    if d.Exists("1") then Debug.Print d("1")
    debug.print d.count
End Sub
还要注意,键是一个字符串。您不希望整数像数组一样作为索引。d(1)只是一个可以放在任何地方的条目,使用键字符串
“1”

这是因为使用
d(1)
可以直接访问对应于“1”键的字典项,如果没有这样的键,则VBScript会在引擎盖下创建它。这就是为什么随后的
d.count
返回
1

您可以进行以下更深入的测试:

Sub TestDictionary()
    Dim d As Dictionary
    Set d = New Dictionary

    Debug.Print d.count     '--> returns 0
    Debug.Print d.keys(0)   '--> returns an error, there are no keys, yet
    Debug.Print d(4)        '--> returns "", i.e. the not defined item associated with the newly created key (which is "4")
    Debug.Print d.keys(0)   '--> returns "4", i.e. the first (and only) dictionary key
    Debug.Print d.keys(1)   '--> returns an error, since there's only one item in the dictionary
    Debug.Print d.Exists(1) '--> returns False, since there's no "1" key in the dictionary
    Debug.Print d.Exists(4) '--> returns True, since there's a "4" key in the dictionary
    Debug.Print d.count     '--> 1, since the third statement created a dictionary item

End Sub
底线:使用
Dictionary
Count
属性了解它是否有任何项,如果您正在查找特定的键,则使用
Exist(key)
属性