FIX: ReDim Preserve Fails on Uninitialized Arrays

ID: Q194617


The information in this article applies to:


SYMPTOMS

After you've used Redim Preserve to re-dimension a dynamic array and run the application, it terminates with the following error:

"Runtime Error 5: "Invalid Procedure Call or Argument".


CAUSE

You cannot use Redim Preserve on a dynamic array that has not been initialized.


RESOLUTION

The workaround is to check the value of the upper bound of the array and, if it is not initialized (the upper bound will have a value of -1), use a Redim statement without Preserve. Here is the sample code that demonstrates this workaround:


   a = Array()
   b = UBound(a)    'get value of largest available array subscript

   If (b <> -1) Then   '-1 is the return value of a uninitialize array
       ReDim Preserve a(5)
   Else
       ReDim a(5)          'no elements exist in array use ReDim
   End If 


STATUS

Microsoft has confirmed this to be a bug in the Microsoft products listed at the beginning of this article. This bug has been corrected in Microsoft Visual Basic Learning, Professional, and Enterprise Editions for Windows, version 6.0, Service Pack 1. Microsoft has confirmed this to be a problem in the Microsoft products listed at the beginning of this article.


MORE INFORMATION

Steps to Reproduce Behavior

  1. Create a Standard EXE project in Visual Basic. Form1 is created by default.


  2. Place a CommandButton on Form1 and paste the following code:
    
          Private Sub Command1_Click()
             Dim a As Variant
             a = Array()
             ReDim Preserve a(5)
          End Sub 


  3. Press the F5 key to run the application, and note that the above error appears.



Steps to Reproduce Behavior


REFERENCES

For additional information, please see the following article(s) in the Microsoft Knowledge Base:

Q193092 PRB: 'Invalid Procedure Call' Error with Preserve Keyword

Additional query words: kbDSupport kbVBp600 kbVS600SP1fix kbNoKeyWord


Keywords          : 
Version           : WINDOWS:6.0
Platform          : WINDOWS 
Issue type        : kbbug 

Last Reviewed: May 28, 1999