I have dictionary. Dictionary have array of 8 elements. Can I set new value of existing array in dictionary? My code below:
Option Explicit
Sub test()
Dim dict As Dictionary
Dim arr() As Long
Dim i As Variant
Set dict = New Dictionary
ReDim arr(1 To 8)
dict.Add "L", arr()
dict.Item("L")(3) = 500
For Each i In dict.Item("L")
Debug.Print (i)
Next
End Sub
Line dict.Item("L")(3) = 500
staying array element empty. What I am doing wrong?
Or there is only one true way?
arr(3) = 500
dict.Item("L") = arr
CodePudding user response:
I made it. Trick in user function. Now it's work fine for me. All previous data are preserved without copying
Sub test()
Dim dict As New Scripting.Dictionary
Dim i As Integer, index As Integer
Dim newVal As Long
ReDim arr(1 To 8) As Long
arr(1) = 200
dict.Add "L", arr
index = 3
newVal = 500
dict("L") = updateItem(dict("L"), index, newVal)
For i = LBound(dict("L")) To UBound(dict("L"))
MsgBox dict("L")(i)
Next
End Sub
Function updateItem(ByRef currentItem As Variant, ByRef index As Integer, ByRef newVal As Long)
currentItem(index) = newVal
updateItem = currentItem
End Function
CodePudding user response:
I ran into this issue once.
You can't change a single value in an array of a dictionary, you have to change the whole array
so this should work
Sub test()
Dim dict As Dictionary
Dim arr() As Long
Dim i As Variant
Set dict = New Dictionary
ReDim arr(1 To 8)
arr(3) = 500
dict.Add "L", arr()
For Each i In dict.item("L")
Debug.Print (i)
Next
End Sub
but what if you want to change a value in an already populated array in a dictionary?
simple
- define a new array to hold the values in the dictionary array
- Make the changes you want
- Load the new array into the dictionary using the .item property (Ex: dict.item("L") = NewArr() )
Sub test()
Dim dict As Dictionary
Dim arr() As Long
Dim i As Variant
Dim newarr() As Long
Set dict = New Dictionary
ReDim arr(1 To 8)
ReDim newarr(1 To 8)
arr(3) = 500
dict.Add "L", arr()
newarr = dict("L")
newarr(3) = 1000
dict.item("L") = newarr()
For Each i In dict.item("L")
Debug.Print (i)
Next
End Sub