Consulting

Results 1 to 3 of 3

Thread: initialize 2d array

  1. #1

    initialize 2d array

    i want to initialize a 2d array. i know i can do it like below but that way is clunky.

    [vba]
    Dim a(2,2)
    a(1,1) = "dog"
    a(1,2) = "cat"
    a(2,1) = "tiger"
    a(2,2) = "lion"
    [/vba]
    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.

    [vba]
    Dim a = Array(("dog", "cat"), ("tiger", "lion"))
    [/vba]

  2. #2
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    [VBA]Dim myArray as Variant
    myArray = Range("A1:AX2").Value[/VBA]

    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

  3. #3
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Try

    [vba]

    ary = [{"Bob","M";"Lynne","F";"Amy","F";"Hannah","F"}]
    [/vba]
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •