在监视窗口中检查字典项后,字典将填充空项

时间:2018-01-25 07:32:13

标签: excel vba excel-vba

最近,我遇到了一个相当奇怪的字典行为。

Sub DictTest()
    Dim iDict As Object
    Dim i As Integer
    Dim strArr() As String
    Set iDict = CreateObject("Scripting.Dictionary")
    strArr = Split("Why does this happen ? Why does this happen over and over ?", " ")
    For i = LBound(strArr) To UBound(strArr)
        iDict(strArr(i)) = strArr(i)
    Next
End Sub

输出是iDict,填充了7个项目: Taken from locals window 但每当我添加手表时:
Add Watch window
它在字典中添加一个空项:
Taken from watch window
为什么添加监视表达式会在字典中创建一个空项?

1 个答案:

答案 0 :(得分:5)

如果使用"What???"键检查字典中的条目,则必须在字典中创建一个条目以显示该条目。

如果您只想检查条目是否存在,请在iDict.Exists("What???")上执行观察。

Adding watch Watch Window

添加手表的操作与以下代码没有区别:

Sub DictTest()
    Dim iDict As Object
    Dim i As Integer
    Dim strArr() As String
    Set iDict = CreateObject("Scripting.Dictionary")
    strArr = Split("Why does this happen ? Why does this happen over and over ?", " ")
    For i = LBound(strArr) To UBound(strArr)
        iDict(strArr(i)) = strArr(i)
    Next
    MsgBox "The value of the 'What???' entry in iDict is '" & iDict("What???") & "'"
End Sub

在以下情况下,更改Dictionary对象的内容与使用Watch Window更改x的值没有什么不同:

enter image description here

在上面的代码中,我使用观察窗口在x声明之前编辑510的{​​{1}}值。