284 Part II Programming Fundamentals
conditions. Dimensioning a dynamic array takes several steps because although the size of
the array isn’t specified until the program is running, you need to make “reservations” for the
array at design time. To create a dynamic array, you follow these basic steps:
- Specify the name and type of the array in the program at design time, omitting the
number of elements in the array. For example, to create a dynamic array named
Temperatures, you type:
Dim Temperatures() As Single - Add code to determine the number of elements that should be in the array at run time.
You can prompt the user by using an InputBox function or a text box object, or you
can calculate the storage needs of the program by using properties or other logic. For
example, the following statements get the array size from the user and assign it to the
Days variable of type Short:
Dim Days As Short
Days = InputBox("How many days?", "Create Array") - Use the variable in a ReDim statement to dimension the array, subtracting 1 because
arrays are zero-based. For example, the following statement sets the size of the
Temperatures array at run time by using the Days variable:
ReDim Temperatures(Days - 1)
Important With ReDim, you should not try to change the number of dimensions in
an array that you’ve previously declared.
- Use the UBound function to determine the upper bound in a For... Next loop, and
process the array elements as necessary, as shown here:
For i = 0 to UBound(Temperatures)
Temperatures(i) = InputBox(Prompt, Title)
Next
In the following exercise, you’ll use these steps to revise the Fixed Array program so that it
can process any number of temperatures by using a dynamic array.
Use a dynamic array to hold temperatures
- Open the Code Editor to display the program code for the Fixed Array project.
- Scroll to the top of the form’s code, in which you originally declared the Temperatures
fixed array. - Remove 0 To 6 from the Temperatures array declaration so that the array is now a
dynamic array.
The statement looks like the following:
Dim Temperatures() As Single