Redim Preserve

ReDim Preserve

Ratings: 1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)

ReDim Preserve is the way to make a dynamic array and maintain the values currently stored in the array by using the ReDim Preserve. If you want to resize your array while remembering all the elements in the array, you must use the Preserve keyword.

ReDim Limitations:

1. ReDim only for Dynamic Array, not Static Arrays

    Example: Dim MyArray() as integer ‘ Ok
                      ReDim MyArray(3)

                       Dim MyArray(2) As Integer ‘Declare as Static Array 
                       ReDim MyArray(3)                ‘This will cause an error

2. Only ReDim Preserve Last Dimension

Example: Dim MyArray() As Integer
                   ReDim MyArray(1, 3)

                  ReDim Preserve MyArray(1, 6) ‘ok
                  ReDim Preserve MyArray(2, 3) ‘But this will cause an error 

3. Cannot use ReDim to Change Data Types
Example: Dim MyArray() As Integer
                   ReDim MyArray(2) As Double ‘This will cause an error

Redim With Preserve keyword


  MyArray(0):zero MyArray(1):one MyArray(2):two

Redim With No Preserve keyword


  MyArray(0): MyArray(1): MyArray(2):two