10

I have a piece of code that does not seem to do what it is expected to do. VBA Arrays are mutable by all means, but it seems that when they are stored into a Dictionary as values of some keys, they are not mutable anymore. Any ideas?

Sub foo()
    Dim mydict As New Dictionary
    mydict.Add "A", Array(1, 2, 3)
    MsgBox mydict("A")(1)
    ''# The above shows 2, which is fine
    mydict("A")(1) = 34
    MsgBox mydict("A")(1)
    ''# The above also shows 2, which is not fine
End Sub
1
  • 1
    The problem is that when you get the array out of the dictionary with mydict("A"), you get a copy and not a reference. See: stackoverflow.com/questions/1402876/… Commented Nov 22, 2010 at 16:38

4 Answers 4

13

It seems you'll need yet to set another var to update the array value.

mArray = mydict.Item(1)
mArray(1) = 34
mydict.Item(1) = mArray
Sign up to request clarification or add additional context in comments.

Comments

2

I created a Procedure to solve the same issue, so I could keep it as a "oneliner":

Private Sub pReplaceDicArray(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)

Comments

0

I would have written this answer as a comment to Mr. Irizarry's answer, but I'm not allowed. Anyway.... I tried writing that last line of code (below) to assign the array to the first item of the dictionary, but it didn't work. The array in that item remained as it was before.

mydict.items(1) = mArray

Based on what I read elsewhere, it seems to have to do with the instance of the dictionary you're calling upon. I changed it to the following line and it worked.

mydict(mydict.keys(1)) = mArray

I'm still not sure why that is the case, but there it is.

Comments

0

Copy the Array and update the value:

mydict("A") = Array(mydict("A")(0), 34, mydict("A")(2))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.