Summary
Dictionaries are a great way collect up lists of items, especially if you don't know how many items you will need to have in your list.
You can think of a dictionary exactly like a classic dictionary, there are two pieces of information. In the classic dictionary there is a word and then the definition. In the dictionary object, there is a key and an item. The key is the word, and the item is the definition.
If you use the "Add" method and you get an error code 457, it means that the key already exists. If there is a chance that you will be trying to add a key that might exist. If you list will have duplicates or you are not sure, you should check to see if the item exists before trying to add the item. See the example below on processing schematics to see how that was done.
- You will need to add the Microsoft Scripting Runtime reference. Scripting How-To: Using the Microsoft Scripting Runtime library with AWR Scripting
Code Snippets
Sub Main Debug.Clear Dim kw As Dictionary Set kw = New Dictionary 'method one of adding a Key and Item. This method will fail if the key already exists. kw.Add("a","cat") 'method two, if doesn't exist, is added. This method will replace the existing item with the new item if the key already exists. kw("b") = "dog" 'error if try to add a key that already exists, so check to see if exists before adding. 'kw.Add("a","wrong") 'assign a new item to the key of b kw("b") = 1 'print out if key "a" exits Debug.Print kw.Exists("a") 'print out if key "c" exits Debug.Print kw.Exists("c") 'prints out the item for key "a" Debug.Print kw("a") 'prints out the key for key number 1 Debug.Print kw.Keys(1) 'prints out the item for key number 1 Debug.Print kw.Items(1) 'keys are 0 based, below loops through all keys and prints key and item. For i = 0 To kw.Count-1 Debug.Print kw.Keys(i) & " = " & kw.Items(i) Next i 'remove items for dictionary by key name kw.Remove("a") Debug.Print "Keys ="& kw.Count 'remove all kw.RemoveAll Debug.Print "Keys =" & kw.Count 'get a list of all keys or items in the dictionary. Note that the variable used must be defined asan array (dimensioned) but not typed dim temp() temp = kw.keys() temp = kw.items() EndSub Simple example to find unique elements and count them for a schematic Sub Main Dim kw As Dictionary Set kw = New Dictionary Dim sch As Schematic Dim ele As Element Debug.Clear Set sch Project.Schematics("Amplifier") For Each ele In sch.Elements tks = Split(ele.Name,".") nm = tks(0) If kw.Exists(nm) = False Then kw(nm) = 1 ' this assignment sets the item number of the key nm Else kw(nm) = kw(nm)+1 'increment count if item alredy exists End If Next ele 'print keys and count for each key. For i = 1 To kw.Count-1 Debug.Print kw.Keys(i) & " = " & kw.Items(i) Next i End Sub