Remove Method

Removes a key, item pair from a Dictionary object.

Syntax

object.Remove(key)

Arguments:

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

  • Key: Required. Key associated with the key, item pair you want to remove from the Dictionary object.

Remarks

An error occurs if the specified key, item pair does not exist.

The following code illustrates use of the Remove method:

Example 1:

Dim d   ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")

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

' Remove the key "b" and its associated item
d.Remove("b")

' Output: Dictionary Object Contains Keys: a,c Items : Athens,Cairo

Example 2:

Function RemoveKey(keyToRemove)
    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 and remove key
    If d.Exists(keyToRemove) Then
        d.Remove(keyToRemove)
        msg = "Key '" & keyToRemove & "' removed."
    Else
        msg = "Key '" & keyToRemove & "' not found."
    End If

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

    RemoveKey = msg
End Function

' Usage
Dim result
result = RemoveKey("y")
' Output: Key 'y' removed. Key: x, Item: Xenon Key: z, Item: Zirconium

Example 3:

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

    ' Add some keys and items.
    d.Add "m", "Moscow"
    d.Add "n", "New York"
    d.Add "p", "Paris"
    d.Add "t", "Tokyo"

    ' Check and remove each key
    For Each key In keysToRemove
        If d.Exists(key) Then
            d.Remove(key)
            msg = msg & "Key '" & key & "' removed."
        Else
            msg = msg & "Key '" & key & "' not found."
        End If
    Next

    ' Display remaining items
    msg = msg & "Remaining items:"
    For Each Key In d.Keys
        msg = msg & "Key: " & Key & ", Item: " & d.Item(Key)
    Next

    RemoveMultipleKeys = msg
End Function

' Usage
Dim keysToRemove
keysToRemove = Array("n", "t", "x")
Dim result
result = RemoveMultipleKeys(keysToRemove)
' Output: Key 'n' removed. Key 't' removed. Key 'x' not found. Remaining items: Key: m, Item: Moscow Key: p, Item: Paris