3
Sub test()
    Dim authDict As Dictionary
    Set authDict = CreateObject("Scripting.Dictionary")

    authDict.Add "Anton", 1
    authDict.Add "Martin", "3"
    authDict.Add "Dave", 1

    testKey = authDict.Exists("Alina") ' False, but adding this Key to dictionary by itself
    testVal = authDict("Alina")
    testKey2 = authDict.Exists("Alina") ' now it true
    testVal2 = authDict("Alina")
End Sub

Why after not exists state dictionary adding this key to dictionary by themselves? How to prevent this

2
  • 1
    I think by using the line testVal = authDict("Alina") , it adds to the dictionary. Commented Aug 6, 2019 at 6:10
  • To avoid this behavior, you'll have to use a custom Dictionary like this one: gist.github.com/florentbr/… Commented Aug 6, 2019 at 10:33

1 Answer 1

4

The issue here is that this line

testVal = authDict("Alina")

will add the item Alina to the dictionary. So you should only run it if it already exists, otherwise it will be created. Use the Exists() method for this like below:

If authDict.Exists("Alina") Then ' False, but adding this Key to dictionary by itself
    testVal = authDict("Alina")
Else
    MsgBox "Alina does not exist"
End If

Why?

By using authDict("Alina") you use the Item property of the Dictionary object submitting Alina as parameter key.

So according to the documentation the item property "Sets or returns an item for a specified key in a Dictionary object.". Since Alina doesn't exist yet there is nothing to return, so it sets it by default.

The documentation of the item property furthermore says:

If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty.

Source: Item property section Remarks.

Sign up to request clarification or add additional context in comments.

4 Comments

My question was - WHY?
@DmitrijHolkin by design. Microsoft coded it that way. You must check if it exists otherwise it will be auto created. That's the default behaviour. There is no explanation to "Why" because it is just because Microsoft programmers chose it to be like that.
@DmitrijHolkin See my edited answer that now includes the answer to "Why?".
@DmitrijHolkin As what was mentioned, it is how it's designed. See Dictionary Documentation clause 5.3 assigning it to a variable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.