6

I was wondering how to fill a multi-dimensional array in Excel VBA. A 1d array can be filled as follows:

Dim myarray as variant

myarray = Array("sheep", "goat", "chicken")

How would I fill each row separately for a multi-dimensional array?

2
  • You can fill a 2-dimensional array quickly by using a dynamic array and entering the data into a range on a worksheet. Then you can simply: array = Range("Range"). For more than 2 dimensions you have to read each value in individually. Commented Nov 7, 2014 at 18:44
  • That's a 1-D array you have there - did you really mean multidimensional? Commented Nov 7, 2014 at 18:50

1 Answer 1

12

You can do this:

Dim a
a = [{1,2;3,4;5,6}]

Limitations:

  • This only works with arrays of type Variant, because [x] is shorthand for Evaluate("x") which means that x is interpreted via Excel, and Excel only returns Variants. So declaring Dim a As Variant or an array Dim a() As Variant works fine. But not any other type of array e.g. Dim a() As String fails.

  • This only works for one specific kind of multi-dimensional array, namely two-dimensional arrays. Not three-, four- etc. dimensional.

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

4 Comments

Really?? That's utterly cool! How on Earth haven't I ever seen this syntax before?!
It should be noted that this only works as shown. A variable that is declared as an array will not be able to be loaded this way. You'll get a compile error: "Can't assign to array."
@Jean-FrançoisCorbett, I just tried it exactly that way and it fails with a compile error.
Dim a() As Variant: a = [{1,2;3,4;5,6}] compiles and executes just fine at my end? Office 2010

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.