Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

vba - Dictionary is populated with an empty item after checking dictionary item in watch window

Recently I've encountered a rather odd dictionary behaviour.

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

The output is iDict populated with 7 items: Taken from locals window But whenever I add watch:
Add Watch window
It adds an empty item to a dictionary:
Taken from watch window
Why does adding a watch expression create an empty item in the dictionary?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you examine the entry in the dictionary with a key of "What???" then naturally an entry must be created in the dictionary in order to show you that entry.

If you want to just check whether an entry exists, then perform a watch on iDict.Exists("What???").

Adding watch Watch Window

Adding a watch is operating no differently to the following code:

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

This changing of the contents of a Dictionary object is no different to using the Watch Window to change the value of x in the following situation:

enter image description here

In the above code, I used the watch window to edit the value of x from 5 to 10 prior to the Debug.Print statement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...