Home > database >  Test if Item of a VBA dictionary is equal to a given value without adding key and item to the dictio
Test if Item of a VBA dictionary is equal to a given value without adding key and item to the dictio

Time:07-09

I need to test if the Item of a VBA Dictionary is equal to a given value, without adding a new key and value to the dictionary.

dict.RemoveAll
MsgBox dict.Exists(key)

MsgBox dict.Exists(key) returns false, the dict is empty.

var = "Hello"
MsgBox var = dict(key)

The MsgBox returns false, because var and the item returned by dict(key) is not equal. But when I again check if the key exists in the dictionary, dict.Exists(key) now returns true.

MsgBox dict.Exists(keys)

Seems to me the equal-Operator not only compares var with the item, but also assigns a new key and item pair to the dict, but i need the dictionary still to be empty. How can i achieve this?

CodePudding user response:

Use exists() to check if a key exists:

Sub foo()

Dim dict As Scripting.Dictionary
Dim key As String
key = "key1"

Set dict = New Dictionary
Debug.Print dict(key) ' -- create a value of Empty for the key
Debug.Print dict.Count ' -- 1 (yikes!)

Set dict = New Dictionary
Debug.Print dict.Exists(key) ' -- no side effects
Debug.Print dict.Count '-- 0 (great!)

End Sub

See also (thanks to Cameron Critchlow):

scripting-dictionary-lookup-add-if-not-present-with-only-one-key-search

Note in your problem you are creating a variable then checking if it is equal to the value of some key (if that key exists!) - so by extension using the method described above, first check if the key exists, then check if it is the same as your variable:

Dim other_key As String
Dim result As Boolean

other_key = "key2"
If dict.Exists(key) Then
    If other_key = dict(key) Then
        result = True
    End If
End If
Debug.Print result

CodePudding user response:

Something along these lines will test all keys and items for a match, while not adding any extra keys.

    Dim Dict As Object
    Set Dict = CreateObject("Scripting.Dictionary")
    Dict.Add "test", "this"
    Dim Var As String
    Dim var2 As String
    Var = "test"
    var2 = "this"
    Dim Key As Variant
    
    For Each Key In Dict
        Debug.Print "var - item", Var = Dict(Key)
        Debug.Print "var - key", Var = Key
        Debug.Print "var2 - item", var2 = Dict(Key)
        Debug.Print "var2 - key", var2 = Key
    Next Key
  • Related