Exists Method

Returns true if a specified key exists in the Dictionary object, false if it does not.

Syntax

object.Exists(key)

Arguments:

  • Object: Required. Always the name of a Dictionary object.

  • Key: Required. Key value being searched for in the Dictionary object.

Remarks

The following example illustrates the use of the Exists method.

Example 1:

Function KeyExistsDemo
    Dim d, msg   ' Create some variables.
    Set d = CreateObject("Scripting.Dictionary")

    ' Add some keys and items.
    d.Add "a", "Athens"
    d.Add "b", "Belgrade"
    d.Add "c", "Cairo"

    ' Check if key exists
    If d.Exists("c") Then
        msg = "Specified key exists."
    Else
        msg = "Specified key doesn't exist."
    End If

    KeyExistsDemo = msg
End Function

' Usage
Dim result
result = KeyExistsDemo
'Output: Specified key exists.

Example 2:

Function CheckMultipleKeys
    Dim d, msg   ' Create some variables.
    Set d = CreateObject("Scripting.Dictionary")

    ' Add some keys and items.
    d.Add "x", "Xenon"
    d.Add "y", "Yttrium"
    d.Add "z", "Zirconium"

    ' Check if keys exist
    msg = ""
    keysToCheck = Array("x", "y", "w")

    For Each key In keysToCheck
        If d.Exists(key) Then
            msg = msg & "Key '" & key & "' exists."
        Else
            msg = msg & "Key '" & key & "' doesn't exist."
        End If
    Next

    CheckMultipleKeys = msg
End Function

' Usage
Dim result
result = CheckMultipleKeys
'Output: Key 'x' exists.Key 'y' exists.Key 'w' doesn't exist.

Example 3:

Function AddKeysIfNotExist
    Dim d, msg   ' Create some variables.
    Set d = CreateObject("Scripting.Dictionary")

    ' Add initial keys and items.
    d.Add "m", "Moscow"
    d.Add "t", "Tokyo"

    ' Check and add keys
    keysToAdd = Array("m", "s", "t")

    For Each key In keysToAdd
        If Not d.Exists(key) Then
            d.Add key, "New City"
        End If
    Next

    ' Display all keys and items
    msg = ""
    For Each key In d.Keys
        msg = msg & "Key: " & key & ", Item: " & d.Item(key)
    Next

    AddKeysIfNotExist = msg
End Function

' Usage
Dim result
result = AddKeysIfNotExist
'Output: Key: m, Item: Moscow Key: t, Item: Tokyo Key: s, Item: New City