I wanted to use an Array as set of values in a Dictionary.
Why is it so, that I cannot change the values in those arrays the same way as I would change them if they were "simple" Arrays?
Let see some examples:
If I create an array, and change the value of n-th element it happens OK.
Sub arrTest()
Dim a As Variant
a = Array(1, 2, 3)
Debug.Print a(0), a(1), a(2)
a(1) = 8
Debug.Print a(0), a(1), a(2)
End Sub
'Output:
' 1 2 3
' 1 8 3
If I try to do the same with my arrays inside a Dictionary, they simply does NOT change, but also don't give an error message. See:
Sub tess()
Dim Dic As Object, Coll As Collection
Set Dic = CreateObject("scripting.dictionary")
Dic.Add "A", Array(1, 2)
Dic.Add "B", 5
Debug.Print Dic.keys()(0), Dic(Dic.keys()(0))(0), Dic(Dic.keys()(0))(1)
Debug.Print Dic.keys()(1), Dic(Dic.keys()(1))
Dic("A")(1) = 8
Dic("B") = 8
Debug.Print Dic.keys()(0), Dic(Dic.keys()(0))(0), Dic(Dic.keys()(0))(1)
Debug.Print Dic.keys()(1), Dic(Dic.keys()(1))
End Sub
'Output:
'A 1 2
'B 5
'
'A 1 2
'B 8
In above example, my non-array value changed to 8 properly, while the value in array remained 2
Why Is it SO , Where is the mistake... etc.?
EDIT
As @FloLie suggested correctly, unfortunately upon interacting with Arrays inside Dictionary, an invisible copy is created, that makes the mess.
However I can't stand multiline clutter for simple operations in my code, so here is my
final solution:
Private Sub mReplaceDicArray(Dic As Object, kEy As Variant, Element As Integer, NewValue)
Dim tempArray As Variant
tempArray = Dic(kEy)
tempArray(Element) = NewValue
Dic(kEy) = tempArray
End Sub
' call as:
' Call mReplaceDicArray(Dic, "A", 1, 8)