Entry
How do you resize a dynamic array without destroying the data already stored?
Dec 27th, 2003 07:18
Gary Winey, Jerry Yoakum, http://msdn.microsoft.com/library/devprods/vs6/vbasic/vbenlr98/vastmredim.htm
You can save the contents on an array when you resize it by inserting
the PRESERVE keyword after the word REDIM. i.e.
ReDim Preserve astrTemp(iArraySize * 2 + 1)
The above example works great for one-dimension arrays. But when you
need to resize multi-dimensional arrays you need to keep the following
in mind:
Redim Preserve preserves the existing values in array elements only
when you resize the last dimension of an array. Resizing other
dimensions or changing the number of dimensions with Redim Preserve
will destroy the contents of existing array elements.
If you have a multi-dimensional array you can specify both rows and
columns in the redim like this:
ReDim Preserve myArray(5, 2)
A simple VB example based on spinning through a recordset:
Dim lngRow As Long
Dim lngCol As Long
Dim varArray As Variant
lngCol = rst.Fields.Count
ReDim varArray(lngCol, lngRow) 'Init array for recordset columns
'Spin some recordset with 5 fields
Do While Not rst.EOF
ReDim Preserve myArray(lngCol, lngRow)
For lngCol = 0 To 4
varArray(lngCol, lngRow) = rst.Fields(lngCol).Value
Next lngCol
lngRow = lngRow + 1
rst.MoveNext
Loop