frequently ask ? : Computers : Programming : Languages : Visual basic

+ Search
Add Entry AlertManage Folder Edit Entry Add page to
Did You Find This Entry Useful?

52 of 65 people (80%) answered Yes
Recently 8 of 10 people (80%) answered Yes


How do you resize a dynamic array without destroying the data already stored?

Dec 27th, 2003 07:18
Gary Winey, Jerry Yoakum,

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