Dictionary class provides some functions beyond those provided by Collection class. A dictionary is a list of key, value pairs. Unlike Collection, Dictionary class is only available via Microsoft Scripting Runtime, a reference to which needs to be added to your project in order to use the class.
Creating a dictionary:
SetDict=NewDictionary SetDict=CreateObject("Scripting.Dictionary")'An alternative
Adding a key and an item to a dictionary:
Dict.Add"Key1","Value1" Dict.Add"Key2","Value2" Dict.AddKey:="Key3",Item:="Value3"
Accessing an item by key:
Value3=MyDict.Item("Key3")
Accessing an item by index:
Index=2 Counter=1 ForEachKeyInDict.Keys IfCounter=IndexThen FoundKey=Key FoundValue=Dict.Item(Key) ExitFor EndIf Counter=Counter+1 Next
Iterating through the keys:
ForEachKeyInDict.Keys Value=Dict.Item(Key) Next
Iterating through the values:
ForEachValueInDict.Items '... Next
Removing an item:
Dict.Remove"Key3"
Removing all items or emptying:
Dict.RemoveAll
Size or number of elements:
Dict.Count
Testing for emptiness:
IfDict.Count=0Then '... EndIf
Changing the key of an item:
Dict.Key("Key1")="Key1a"
Changing the value of an item:
Dict.Item("Key2")="Value2a"
Testing for presence of a key:
IfDict.Exists("Key2")Then '.. EndIf
Using dictionary as a set:
- Associate the dummy value 1 with each element of the set.
- When adding an item, test for existence.
SetDictSet=NewDictionary DictSet.Add"Item1",1 'DictSet.Add "Item1", 1 -- error: the item is already there IfNotDictSet.Exists("Item1")Then DictSet.Add"Item1",1 EndIf DictSet.Remove"Item1"
