Cameel
Cameel

Reputation: 105

Dictionary in VBA is created with empty key value pair

After creating a new dictionary:

Dim teams as Dictionary
Set teams = New Dictionary

I noticed that it already contains empty key - value pair (teams.Count returns value of 1). How can I prevent this from happening or delete this pair? Is this normal behaviour?

Upvotes: 6

Views: 9574

Answers (2)

Keith Twombley
Keith Twombley

Reputation: 1688

I had the same experience and solved it.

I had a Watch expression set for a value in the dictionary. Somehow this kept the empty key/value pair in the dictionary (or kept readding it).

Removing the watch(es) and stepping through the code I now see the dictionary does not have the Empty/Empty item any longer.

Upvotes: 21

user2140173
user2140173

Reputation:

If you are referencing the same Microsoft Scripting Runtime dictionary scrrun.dll as me - Excel 2010.

enter image description here

Then the below code returns 0 as the .Count of items after creation with no manipulation.

Sub SD()
    Dim teams As Dictionary
    Set teams = New Dictionary
    Debug.Print teams.Count
End Sub

I wouldn't know the reason why your dictionary returns 1, however I think a workaround it would be to simply use the .RemoveAll method of the Dictionary object

Sub SD()
    Dim teams As Dictionary
    Set teams = New Dictionary
    teams.RemoveAll
    Debug.Print teams.Count
End Sub

Upvotes: 3

Related Questions