How do I declare an array variable in VBA?

后端 未结 7 675
灰色年华
灰色年华 2020-12-08 20:02

I need to add the var in array

Public Sub Testprog()

Dim test As Variant
Dim iCounter As Integer

If test = Empty Then
    iCounter = 0
    test(iCounter) =         


        
7条回答
  •  离开以前
    2020-12-08 20:38

    Further to RolandTumble's answer to Cody Gray's answer, both fine answers, here is another very simple and flexible way, when you know all of the array contents at coding time - e.g. you just want to build an array that contains 1, 10, 20 and 50. This also uses variant declaration, but doesn't use ReDim. Like in Roland's answer, the enumerated count of the number of array elements need not be specifically known, but is obtainable by using uBound.

    sub Demo_array()
        Dim MyArray as Variant, MyArray2 as Variant, i as Long
    
        MyArray = Array(1, 10, 20, 50)  'The key - the powerful Array() statement
        MyArray2 = Array("Apple", "Pear", "Orange") 'strings work too
    
        For i = 0 to UBound(MyArray)
            Debug.Print i, MyArray(i)
        Next i
        For i = 0 to UBound(MyArray2)
            Debug.Print i, MyArray2(i)
        Next i
    End Sub
    

    I love this more than any of the other ways to create arrays. What's great is that you can add or subtract members of the array right there in the Array statement, and nothing else need be done to code. To add Egg to your 3 element food array, you just type

    , "Egg"

    in the appropriate place, and you're done. Your food array now has the 4 elements, and nothing had to be modified in the Dim, and ReDim is omitted entirely.

    If a 0-based array is not desired - i.e., using MyArray(0) - one solution is just to jam a 0 or "" for that first element.

    Note, this might be regarded badly by some coding purists; one fair objection would be that "hard data" should be in Const statements, not code statements in routines. Another beef might be that, if you stick 36 elements into an array, you should set a const to 36, rather than code in ignorance of that. The latter objection is debatable, because it imposes a requirement to maintain the Const with 36 rather than relying on uBound. If you add a 37th element but leave the Const at 36, trouble is possible.

提交回复
热议问题