Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare an array variable in VBA?

Tags:

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) = "test" Else     iCounter = UBound(test) End If End Sub 

Getting error at test(iCounter) = "test"

Please suggest some solution

like image 698
Vba Dev Avatar asked Apr 17 '11 03:04

Vba Dev


People also ask

How do you declare an array variable?

To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.

How do I initialize an array in Excel VBA?

To initialize an array variable by using an array literalIf you supply both the upper bound and the values, you must include a value for every element from index 0 through the upper bound. Notice that you do not have to specify the index upper bound if you supply element values in an array literal.


Video Answer


2 Answers

Generally, you should declare variables of a specific type, rather than Variant. In this example, the test variable should be of type String.

And, because it's an array, you need to indicate that specifically when you declare the variable. There are two ways of declaring array variables:

  1. If you know the size of the array (the number of elements that it should contain) when you write the program, you can specify that number in parentheses in the declaration:

    Dim test(1) As String   'declares an array with 2 elements that holds strings 

    This type of array is referred to as a static array, as its size is fixed, or static.

  2. If you do not know the size of the array when you write the application, you can use a dynamic array. A dynamic array is one whose size is not specified in the declaration (Dim statement), but rather is determined later during the execution of the program using the ReDim statement. For example:

    Dim test() As String Dim arraySize As Integer  ' Code to do other things, like calculate the size required for the array ' ... arraySize = 5  ReDim test(arraySize)  'size the array to the value of the arraySize variable 
like image 69
Cody Gray Avatar answered Sep 22 '22 19:09

Cody Gray


Further to Cody Gray's answer, there's a third way (everything there applies her as well):

You can also use a dynamic array that's resized on the fly:

Dim test() as String Dim arraySize as Integer  Do While someCondition     '...whatever     arraySize = arraySize + 1     ReDim Preserve test(arraySize)     test(arraySize) = newStringValue Loop 

Note the Preserve keyword. Without it, redimensioning an array also initializes all the elements.

like image 45
RolandTumble Avatar answered Sep 22 '22 19:09

RolandTumble