< Previous lesson | Table of Content | Content of this Chapter | Next lesson >

Declaring VB Array

To declare an array in VB6, you need to specify only the name of the array and optionally the type of the array. If you do not specify the type of the array, it will automatically be assigned as Variant type.

For example:

Dim arr()
Dim myVector(1 to 20) as Integer
Dim MyMatrix(1 to 3, 3 to 10) as Long

The first example you only declare the name of the array (i.e. arr ) without specifying the type of the array. Thus arr is a variant type array. The second example above declares a vector with lower bound 1 and upper bound 20 of Integer type. Thus this array contains 20 elements. The third example, array MyMatrix is two dimensional arrays consist of 3 rows and 8 columns. The column indexing start at 3 with upper bound 10.

If you do not specify the size of the array variable during declaration, you need to redefine the same array right before using it. This is called dynamic array. If you specify the size of the matrix during declaration, the size of the matrix is fixed when the program run. This kind of array is called static array. The second and third examples above are also examples of static array. Static array can only be dimensioned once. You cannot change the size of the array during running time. If you do know exactly how large is the size of the array, use dynamic array.

Before using an array variable, you need to specify the size of the array as the second and third example above. To obtain the lower bound and upper bound of a matrix, you use keywords: LBound and UBound respectively.
Example:

Dim MyMatrix(1 to 4, 3 to 10) as Long
Dim URow as Integer, LRow as Integer
Dim UCol as Integer, LCol as Integer

LRow = LBound(MyMatrix, 1) return 1
URow = UBound(MyMatrix, 1) return 4
LCol = LBound(MyMatrix, 2) return 3
UCol = UBound(MyMatrix, 2) return 10

To redefine the size of the variable during running time (to make it dynamic array), you use keyword ReDim and optionally Preserve .


Example:
Dim j as Integer
Dim myArray()

j = 100
ReDim myArray(1 to j)

You use the keyword Preserve if you want to keep the contents of the array. If you do not use the keyword Preserve and you redefine the array, all the values contents in that array will be deleted.

< Previous lesson | Table of Content | Content of this Chapter | Next lesson >