Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically sign up today!
The most commonly used array in VB6 programs is a static array. It has a fixed size, which is assigned when the array is declared, and that size remains the same throughout program execution. Another type of array, called a dynamic array, lets you change its size while the program is running. This can be very useful when you don't know ahead of time how much data the array will store.
To create a dynamic array, use the Dim statement; however, be sure that the parentheses are left empty. This statement declares a dynamic array of type Integer:
Dim MyArray() As Integer
Before using the array, you must set its size using the ReDim statement:
Now you can use the dynamic array just like any other array. When you need to change its size, use ReDim again. For instance:
By default, changing the size of a dynamic array erases all the data in the array. If you want to preserve the data, include the Preserve keyword:
ReDim Preserve MyArray(250)
This will preserve data in the original elements of the array--elements 0 through 100 in this example. If you reduce the size of the array, data in elements that are cut off are not preserved.
You can use dynamic arrays with any VB data type and with multi-dimensional as well as one-dimensional arrays.