Declaring - Dynamic Size
Dynamic arrays do not have a fixed size and can be resized at run-time.
These are also known as Variable Arrays or Variable-Length Arrays.
This type of array is very useful when you don't know the exact size of the array at design time.
You can declare a dynamic array using the Dim statement.
When you need to define the size of the array you can use the ReDim statement.
You can declare a dynamic array by using an empty set of parentheses.
Dynamic arrays are always declared with empty parentheses.
The parentheses must always be attached to the variable, never the data type.
Dynamic Array - String Data Type Array
These two lines create an array that can contain 4 string elements.
Dim aStrings() As String 'this is a String Array
Dynamic Array - Variant Data Type Array
These two lines create an array that can contain 4 elements of any data type.
Dim aVariants() As Variant 'this is a Variant Array
Dynamic Array - Variant Data Type
A Variant that is not declared as an array can still contain an array.
The first line creates a single variable (not an array) that can contain any data type.
The second line declares an array containing 4 elements and assigns it to this single variable.
Dim avNumbers As Variant 'this is just a Variant
ReDim avNumbers(2) 'creates an array of Variants
ReDim avNumbers(3) As Long 'creates an array of Longs
This approach declares your array as a single variable and then creates the array.
When you declare as a Variant Data Type you can define the data type when the array is created.
After declaring an array it will contain default values.
Numeric arrays will contain the number 0.
String arrays will contain the Empty String "".
Variant arrays will contain the Empty keyword.
Object arrays will contain the Nothing keyword.
Explicit Lower Bound
It is possible to explicitly declare the lower bound of your dynamic array.
The following two lines are equivalent and both these arrays contain 101 elements.
The index values range from 0 to 100.
ReDim myArray(0 to 100)
A dynamic array does not have a pre-defined number of elements
Resizing arrays at run-time can be very inefficient. If adding a lot of data dynamically do not resize the array after every new element but after every 10 or so.
Never Use Option Base 1
If you want all your arrays to start at the index number 1 (instead of 0) you can explicitly declare the lower bound to be 1.
More details can be found on the Option Base 1 page.
The following line of code will declare an array containing exactly 100 elements with the index values from 1 to 100.
Dim myArray(1 To 100) As Integer
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext