Search code examples
arraysvbams-accesserase

Subscript out of Range after Erase


The following minimal example crashes until the Erase statement is commented out. Why?
(I can't find this documented.)

Sub Test()
  Dim a1() As Integer
  ReDim a1(0 To 2)
  Erase a1
  Debug.Print a1(1)       ' Subscript out of range (Run-time error '9')
  Debug.Print LBound(a1)  ' Subscript out of range (Run-time error '9')
  Debug.Print UBound(a1)  ' Subscript out of range (Run-time error '9')
End Sub

Should I replace the Erase with For i = LBound(a1) to UBound(a1): a1(i) = 0: Next i?


Solution

  • From the linked documentation:

    Erase frees the memory used by dynamic arrays. Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions by using a ReDim statement.


    The behavior of Erase is different for static and dynamic arrays. For static arrays, the command resets all members to their default value (0 for numbers, empty string for strings). For dynamic array, it removes all members, the situation is the same as if you never used a Redim.

    In your case, where you have a dynamic array, there is no need to use Erase. If you want to reset all values of the array after using it, simply issue another Redim-statement, it doesn't matter if the size stays the same. Unless you use Redim with the keyword Preserve, all members are created with the default value. The following statement will do the trick:

    ReDim a1(LBound(a1) To UBound(a1))