Chapter 11 Using Arrays to Manage Numeric and String Data 287
You’ve practiced using the two most common array types in Visual Basic programming.
When you write your own programs, you’ll soon use much larger arrays, but the concepts
are the same, and you’ll be amazed at how fast Visual Basic can complete array-related
computations.
Preserving Array Contents by Using ReDim Preserve
In the previous exercise, you used the ReDim statement to specify the size of a dynamic array
at run time. However, one potential shortcoming associated with the ReDim statement is that
if you redimension an array that already has data in it, all the existing data is irretrievably
lost. After the ReDim statement is executed, the contents of a dynamic array are set to
their default value, such as zero or null. Depending on your outlook, this can be considered
a useful feature for emptying the contents of arrays, or it can be an irksome feature that
requires a workaround.
Fortunately, Visual Basic provides the Preserve keyword, which you use to preserve the
data in an array when you change its dimensions. The syntax for the Preserve keyword is
as follows:
ReDim Preserve ArrayName(Dim1Elements, Dim2Elements, ...)
In such a ReDim statement, the array must continue to have the same number of dimensions
and contain the same type of data. In addition, there’s a caveat that you can resize only
the last array dimension. For example, if your array has two or more dimensions, you can
change the size of only the last dimension and still preserve the contents of the array.
( Single-dimension arrays automatically pass this test, so you can freely expand the size of
dynamic arrays by using the Preserve keyword .)
The following examples show how you can use Preserve to increase the size of the last
dimension in a dynamic array without erasing any existing data contained in the array.
If you originally declared a dynamic string array named Philosophers by using the syntax:
Dim Philosophers() As String
you can redimension the array and add data to it by using code similar to the following:
ReDim Philosophers(200)
Philosophers(200) = "David Probst"
You can expand the size of the Philosophers array to 301 elements (0–300), and preserve the
existing contents, by using the following syntax:
ReDim Preserve Philosophers(300)