O'Reilly logo

VBScript in a Nutshell, 2nd Edition by Ron Petrusha, Matt Childs, Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

Dictionary.Add Method

Syntax

                  dictionaryobject.Add key, 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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required