VBA Dictionary Change
Dictionaries are lookup structures. Typically, they are filled with data and, once that is done, they are used to look up data. Normally, the key/items pairs in the dictionaries don't change a lot.
However, changes are possible. In a key/item pair, items can be changed. Keys cannot.
1 2 3 4 5 6 | D("Key") = "Item1" MsgBox D.Item("Key") 'shows Item1 D("Key") = "Item2" MsgBox D.Item("Key") 'shows Item2 |
Implicit adding can be useful when changing the dictionary. Imagine you have a dictionary that is used to contain statistics.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Dim D As New Dictionary D("Statistic1") = D("Statistic1") + 1 'right hand side D("Statistic1") creates the key/item pair and chooses Integer as type for item D("Statistic2") = D("Statistic2") & "A" 'right hand side D("Statistic2") creates the key/item pair and chooses String as type for item MsgBox D.Item("Statistic1") 'shows 1 MsgBox D.Item("Statistic2") "shows A D("Statistic1") = D("Statistic1") + 1 D("Statistic2") = D("Statistic2") & "B" MsgBox D.Item("Statistic1") 'shows 2 MsgBox D.Item("Statistic2") "shows B |
Be careful whit implicit adding. The behavior of the code depends on the compare mode.
1 2 3 4 | D.CompareMode = BinaryCompare D("Statistic1") = 5 D("<span class="cJSONGrammar">s</span>tatistic1") = D("Statistic1") + 1 'this will not update Statistic1 |
1 2 3 4 | D.CompareMode = TextCompare D("Statistic1") = 5 D("Statistic1") = D("Statistic1") + 1 'this will update Statistic1 |
A key/item pair can be removed.
1 2 3 4 | D("Key1") = "Item1" D("Key2") = "Item2" D.Remove "Key1" |
All key/item pairs can be removed at once.
1 2 3 4 | D("Key1") = "Item1" D("Key2") = "Item2" D.RemoveAll() |
After RemoveAll
, the (reference to the) dictionary still exists in the memory. It is not Nothing
. Be careful when using a dictionary as an item in a key/item pair. Have a look at the following two pieces of code. The first one probably does not behave as you would expect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Dim D1 As New Dictionary Dim D2 As New Dictionary D1.Add "A1", "Item1" D1.Add "A2", "Item2" D.Add "D1", D1 D1.RemoveAll D1.Add "A1", "Item3" D1.Add "A2", "Item4" D.Add "D2", D1 MsgBox D.Item("D1").Item("A1") 'shows Item3, not Item1 MsgBox D.Item("D1").Item("A2") 'shows Item4, not Item2 MsgBox D.Item("D2").Item("A1") 'shows Item3 MsgBox D.Item("D2").Item("A2") 'shows Item4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Dim D1 As New Dictionary Dim D2 As New Dictionary D1.Add "A1", "Item1" D1.Add "A2", "Item2" D.Add "D1", D1 Set D1 = Nothing D1.Add "A1", "Item3" D1.Add "A2", "Item4" D.Add "D2", D1 MsgBox D.Item("D1").Item("A1") 'shows Item1 MsgBox D.Item("D1").Item("A2") 'shows Item2 MsgBox D.Item("D2").Item("A1") 'shows Item3 MsgBox D.Item("D2").Item("A2") 'shows Item4 |