Tip:
Highlight text to annotate it
X
In this lesson, we will discuss how to adjust the number of elements in an array using the ReDim statement.
When we declare arrays using the Dim statement, a specific amount of memory is set aside to store data.
For example: Dim b(3) As Double creates an array with four elements.
A certain amount of memory is allocated for each element in the array.
An array that is declared using the Dim statement has a fixed number of elements, and therefore a fixed amount of memory is allocated
for that array.
We are unable to change the number of elements in array b later in the program.
However if we use the ReDim statement instead of Dim to declare an array, we are allowed to change the number of elements in the
array whenever we wish.
When we change the number of elements in an array, we are changing the amount of memory allocated to store data in that array.
This process of changing the number of elements in an array is called "redimensionalizing" the array.
ReDim f(2) As Double creates an array that initially contains three elements.
Let’s assign three values to these elements.
If later in our program we want to increase the number of elements in array f from three to five, we can type:
ReDim Preserve f(4) As Double
Two additional elements, f(3) and f(4), are created and are assigned a default value of 0.
The use of the Preserve keyword prevents the data that already exists in the array f from being erased during the redimensionalizing
process.
If Preserve were omitted, all five elements in f would be set to the value 0.
We can assign data to the new elements in the usual manner.
If we tried typing f(3) = 11 and f(4) = 13 before redimensionalizing the array f, we would have received an error message since elements f(3)
and f(4) did not yet exist.
We also can make arrays smaller using the ReDim statement.
ReDim Preserve f(3) As Double redimensionalizes the array f down to 4 elements.
The data stored in the now no-existent f(4) element is lost forever.
If you now try to display the data in f(4) using a message box, you will receive an error message stating that the subscript is out of range.
Element f(4) no longer exists.