Zev Spitz
Zev Spitz

Reputation: 15327

Modifying array within Dictionary is ignored

The following code:

Dim arr As Variant, item As Variant
arr = Array(1)
arr(0) = 5
For Each item In arr
    Debug.Print item
Next

prints 5; it seems to successfully modify the contents of the array.

However, if I create a Dictionary, and place an array at one of the dictionary keys:

Dim dict As New Scripting.Dictionary, item As Variant
dict("a") = Array(1)
dict("a")(0) = 5
For Each item In dict("a")
    Debug.Print item
Next

the array is read-only; the edit is ignored, and the code prints 1 -- the original value.

Why can I modify the elements of an array referenced through a variable, but not those of an array referenced through a call to Dictionary.Item; and how can I resolve this?

Upvotes: 0

Views: 57

Answers (3)

Zev Spitz
Zev Spitz

Reputation: 15327

I can use nested dictionaries instead of an array within a dictionary:

Dim dict As New Scripting.Dictionary, item As Variant
Set dict("a") = New Dictionary
dict("a")(0) = 5
For Each key In dict("a")
    Debug.Print dict("a")(key)
Next

Upvotes: 0

dbmitch
dbmitch

Reputation: 5386

Just to clarify your questions with an example expanding on @omegastripes answer and my comments on referencing variables in VBA

COMMENTS: You're setting the value of the dictionary. You're NOT setting the value of the array item. You cannot set the dictionary item to a reference to the array - you can set an array value then set the dictionary to the array item - but that is using the value not the reference

Here's an example to show that VBA does not store a reference to the variable when you assign it to another variable

Sub Test()

    Dim dict As Object, item As Variant

    Dim arr

    Set dict = CreateObject("Scripting.Dictionary")

    dict("a") = Array(1)

    arr = dict("a")
    arr(0) = 5
    dict("a") = arr
    For Each item In dict("a")
        Debug.Print item
        ' Prints 5
    Next

    ' Change array contents
    arr(0) = 10
    For Each item In dict("a")
        Debug.Print item
        ' Still Prints 5
    Next

End Sub

Results in Immediate Window will be:

5
5

Upvotes: 0

omegastripes
omegastripes

Reputation: 12612

Here is working example with dictionary:

Sub Test()

    Dim dict As New Scripting.Dictionary, item As Variant
    dict("a") = Array(1)
    Dim arr
    arr = dict("a")
    arr(0) = 5
    dict("a") = arr
    For Each item In dict("a")
        Debug.Print item
    Next

End Sub

And also take a look at nested arrays:

Sub TestArrays()

    Dim a() As Variant, item As Variant
    a = Array("")
    a(0) = Array(1)
    a(0)(0) = 5
    For Each item In a(0)
        Debug.Print item
    Next

End Sub

Upvotes: 1

Related Questions