PDA

View Full Version : initialize 2d array



sandbagger
03-16-2009, 07:54 PM
i want to initialize a 2d array. i know i can do it like below but that way is clunky.


Dim a(2,2)
a(1,1) = "dog"
a(1,2) = "cat"
a(2,1) = "tiger"
a(2,2) = "lion"

the syntax below is incorrect but is there a way to do something like this in a single line of code? i have to initialize an array of size ~2x50.


Dim a = Array(("dog", "cat"), ("tiger", "lion"))

mikerickson
03-16-2009, 09:43 PM
Dim myArray as Variant
myArray = Range("A1:AX2").Value

will fill the array with the values in A1:AX2.

Other than that, arrays can't be bulk loaded. Perhaps something like this will work for you.

Dim HardCodedData As Variant
Dim myArray() As Long
Dim i As Long, j As Long

HardCodedData = Array(Array(11, 12, 13, 14, 15, 16, 17), _
Array(21, 22, 23, 24, 25, 26, 27), _
Array(31, 32, 33, 34, 35, 36, 37))

Rem note HardCodedData is a 1-D array, each of the elements are also 1-D arrays
Rem myArray is a true 2D array

ReDim myArray(0 To UBound(HardCodedData), 0 To UBound(HardCodedData(1)))


For i = 0 To UBound(myArray, 1)
For j = 0 To UBound(myArray, 2)
myArray(i, j) = HardCodedData(i)(j)
Next j
Next i

Bob Phillips
03-17-2009, 01:52 AM
Try



ary = [{"Bob","M";"Lynne","F";"Amy","F";"Hannah","F"}]