1. Dictionary Item can hold an array;
2. The item associated with a particular key can be changed.
It seems that it is possible to place an array in Dictionary and work with the array as usual, read and write. But it is not so. Here's an example:
Sub TestArrInDic()
Dim dic As New Dictionary 'requires reference to 'Microsoft Scripting Runtime'
Dim x
'place an array of variants in dictionary
dic(1) = Array(7, "foo", Now) 'dic(1) is a shortcut to dic.Item(1) as Item is default property
'verify that Dictionary Item is really an array
Debug.Print TypeName(dic(1)) 'Variant()
Debug.Print LBound(dic(1)), UBound(dic(1)) '0 2
For Each x In dic(1): Debug.Print x,: Next '7 foo (current date and time)
Debug.Print
'try to assign new values to array elements
dic(1)(0) = -2
dic(1)(1) = True
dic(1)(2) = 3.14
'show array elements
For Each x In dic(1): Debug.Print x,: Next '7 foo (the same date and time)
Debug.Print
End Sub
Open in new window
The elements has not changed and you have received no error!
To workaround you have to extract the whole array to a variable, change it and place it back as a whole:
Sub TestArrInDic2()
Dim dic As New Dictionary 'requires reference to 'Microsoft Scripting Runtime'
Dim x
'place an array of variants in dictionary
dic(1) = Array(7, "foo", Now)
'show array elements
For Each x In dic(1): Debug.Print x,: Next '7 foo (current date and time)
Debug.Print
'retrieve the whole array from Dictionary item
x = dic(1)
'assign new values to array elements
x(0) = -2
x(1) = True
x(2) = 3.14
'put the array back to Dictionary Item
dic(1) = x
'show array elements
For Each x In dic(1): Debug.Print x,: Next '-2 True 3.14
Debug.Print
End Sub
Open in new window
Another workaround is to create a class containing an array and place an instance of the class in Dictionary.
Elements of the array will be accessed through property of the class. This method is more complicated in programming but it eliminates the need to rewrite the whole array when you need to change one element.
Conclusion: the elements of array placed in Dictionary Item are read-only. The array can be changed only as a whole.
I can explain it as following: if notation dic.Item(1) appeares not immeadetely before assign operator "=" (in the examples above the expression is followed by indexation) then VB treates it as a part of expression and uses Get clause of Dictionary Item property. So a COPY of item content is created, assignment is made to the copy. By the end of statement the copy is wiped like any intermediate data.
By the way, the behavior of Collection is the same:
Sub TestArrInCol()
Dim x
With New Collection
.Add Array(7, "foo", Now)
.Item(1)(0) = -2
.Item(1)(1) = True
.Item(1)(2) = 3.14
For Each x In .Item(1): Debug.Print x,: Next '7 foo (current date and time)
End With
End Sub
Open in new window
Happy coding!
Alex