Link to home
Create AccountLog in
Avatar of lucavilla
lucavillaFlag for Italy

asked on

oneliner 2D array creation in Excel VBA?

How can I declare a 2D array specifying all the values with a single line of code in Excel VBA?
Avatar of Steve
Steve
Flag of United Kingdom of Great Britain and Northern Ireland image

You cannot do this in VBA...

you have to loop through the array entering the value into each value:
Such as below...

Dim MyArray(1 to 15, 1 to 15) as string
for x = lBound(MyArray,1) to ubound(MyArray,1)
    for y = lBound(MyArray,2) to ubound(MyArray,2)   
        MyArray(x,y) = "value"
    next y
next x

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Rory Archibald
Rory Archibald
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Or if your data is in a range, say A1:C27 on your worksheet:
Dim vData As Variant
    vData = Range("A1:C27").Value

Open in new window

Or you can use the Array function:
vData = Array(Array(1, 2, 3), Array(4, 5, 6), Array(5, 6, 7))

Open in new window

but this is not as concise as Rory's, and the elements have to be accessed by the less obvious
vData(i)(j)

Open in new window

rather than
vData(i, j)

Open in new window

as in the other examples
Avatar of lucavilla

ASKER

I asked here because the following 2D array declaration returns a "Run-time error '13': Type Mismatch error"

aNomeFogli = [{"Istruttoria","Note" & Chr(10) & "(Opzionale)"; "Stipula","T"; "Post Stipula","L"}]

I now discovered that the cause is that Chr(10).
How could I avoid the error keeping it and keeping the declaration of minimalist lenght?
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.