2

I want to create a multi-dimensional array where I assign all the values at once instead of going through all the array coordinate values one by one. I believe this is called setting 'array literals'. Anyway, all my variables are string values. The code below doesn't give me a syntax error but when I step through I'm getting a "Compile error: Can't assign to array" message on pkg= line. How do I make this work?

Sub test_array2()

Dim pkg(2, 2) As String

pkg = [{"PRetail","Retail Packaged"};{"PFoodservice","Foodservice 
Packaged"}]

Debug.Print pkg(1, 1)

End Sub
1
  • 3
    Just a warning about doing this this way - the "identifier" (i.e. the part within the [ ... ]) is limited to 255 characters. You get a "Identifier too long" syntax error if you exceed the limit. Commented Dec 21, 2017 at 21:58

1 Answer 1

5

You cannot assign directly to an array like that, so you need to use a variant:

Sub test_array2()

    Dim pkg As Variant

    pkg = [{"PRetail","Retail Packaged";"PFoodservice","FoodservicePackaged "}]

    Debug.Print pkg(1, 1)

End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

You can assign to a non-variant array, just not a fixed size one like Dim pkg(2, 2). In this case the array also has to contain Variants due to the return type of the [], so the correct declaration would be Dim pkg() As Variant, at which point the difference with Dim pkg As Variant is a technicality.

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.