5

I have an array in VBA that I would like to append, and it is the item of a dictionary. It is assigned like this:

dict.Add Key:=arr(i, 1), Item:=Array(arr(i, 2), arr(i, 3), arr(i, 4), arr(i, 5), arr(i, 6), arr(i, 7), arr(i, 8))

However I understand that arrays in VBA are very static, and can't simply be appended. Is there a way for me to unpack the elements of the array, and then create a new array (with the new item) and assign it back as the dictionary's item?

Any help is appreciated.

1
  • Is there a way that you can anticipate the maximum length of the array so you can preallocate? Commented Jun 8, 2018 at 11:53

1 Answer 1

3

You can ReDim with Preserve but only on a copy of the dictionary item. Apparently, redim'ming a variant array dictionary Item in place is not allowed..

Sub meh()
    Dim i As Long, itm As Variant, dict As Object

    Set dict = CreateObject("scripting.dictionary")

    dict.Add Key:=("a"), Item:=Array(1, 2, 3)

    For i = LBound(dict.Item("a")) To UBound(dict.Item("a"))
        Debug.Print dict.Item("a")(i)
    Next i

    itm = dict.Item("a")
    ReDim Preserve itm(LBound(itm) To UBound(itm) + 1)
    itm(UBound(itm)) = "new"
    dict.Item("a") = itm

    For i = LBound(dict.Item("a")) To UBound(dict.Item("a"))
        Debug.Print dict.Item("a")(i)
    Next i
End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

The 'redim preserve...' line gives me a syntax error. I've been over it many times and can't spot what's wrong.
I've found and bandaided the problem although I don't know is this is more trouble than it's worth.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.