Name
Dictionary.Add Method
Syntax
dictionaryobject.Addkey,item
dictionaryobjectUse: Required
Data Type: Dictionary object
A reference to a Dictionary object.
keyUse: Required
Data Type: Any
A key value that’s unique in the Dictionary object.
itemUse: Required
Data Type: Any
The item to be added to the dictionary.
Description
Adds a key and its associated item to the specified Dictionary object.
Rules at a Glance
If the key isn’t unique, runtime error 457, “This key is already associated with an element of this collection,” is generated.
itemcan be of any data type, including objects and other Dictionary objects.
Example
The example uses a Dictionary object to store state abbreviations and their corresponding state names:
Dim StateCode, StateName
Dim StateDict
Dim Key
Set StateDict = CreateObject("Scripting.Dictionary")
StateCode = "CA"
StateName = "California"
StateDict.Add StateCode, StateName
StateCode = "NY"
StateName = "New York"
StateDict.Add StateCode, StateName
StateCode = "MI"
StateName = "Michigan"
StateDict.Add StateCode, StateName
Key = "NY"
MsgBox StateDict.Item(Key)Programming Tips and Gotchas
The order of members within a Dictionary object is officially undefined. That is, you can’t control the position of individual members, nor can you retrieve individual members based on their position within the Dictionary object. Your code, in short, should make no assumptions about the position of individual elements within the Dictionary objects.
Once you add a key and its associated data item, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access