Add Method

Adds a key and item pair to a Dictionary object.

Syntax

object.Add(key, item)

Arguments:

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

  • Key: Required. The key associated with the item being added.

  • Item: Required. The item associated with the key being added.

Remarks

An error occurs if the key already exists.

The following example illustrates the use of the Add 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"
' Output: Dictionary Object Contains Keys: a,b,c Items: Athens,Belgrade,Cairo

Example 2:

Dim d
Set d = CreateObject("Scripting.Dictionary")

' Add some keys and items.
If Not d.Exists("a") Then
    d.Add "a", "Athens"
End If

If Not d.Exists("b") Then
    d.Add "b", "Belgrade"
End If

If Not d.Exists("c") Then
    d.Add "c", "Cairo"
End If
' Output: Dictionary Object Contains Keys: a,b,c Items: Athens,Belgrade,Cairo

Example 3:

Dim d
Set d = CreateObject("Scripting.Dictionary")

Dim arrKeys, arrItems
arrKeys = Array("a", "b", "c")
arrItems = Array("Athens", "Belgrade", "Cairo")

For i = 0 To UBound(arrKeys)
    d.Add arrKeys(i), arrItems(i)
Next
' Output: Dictionary Object Contains Keys: a,b,c Items: Athens,Belgrade,Cairo

Note:

Directly using new object creation in dictionary add call is not supported.

For example:

Set d = CreateObject("Scripting.Dictionary")

'Create an object first and then add it to the dictionary.

Set obj = new class

d.add key, obj This is supported.