Name
Dictionary.Add Method
Syntax
dictionaryobject
.Addkey
,item
dictionaryobject
Use: Required
Data Type: Dictionary object
A reference to a Dictionary object.
key
Use: Required
Data Type: Any
A key value that’s unique in the Dictionary object.
item
Use: 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.
item
can 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, ...
Get VBScript in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.