Declaring dynamic arrays

A dynamic array doesn't have a preset number of elements. You declare a dynamic array with a blank set of parentheses:

Dim MyArray() As Integer

Before you can use a dynamic array in your code, however, you must use the ReDim statement to tell VBA how many elements are in the array. This is often done by using a variable, the value of which isn't known until the procedure is executing. For example, if the variable * contains a number, you can define the array's size by using this statement:

ReDim MyArray (1 to x)

You can use the ReDim statement any number of times, changing the array's size as often as you need to. When you change an array's dimensions the existing values are destroyed. If you would like to preserve the existing values, use ReDim Preserve. For example:

ReDim Preserve MyArray (1 to y)

Arrays crop up later in this chapter when I discuss looping ("Looping blocks of instructions").

4 PREV

NEXT

0 0

Post a comment