Dynamic Arrays

If you declare a dynamic array, then you do not specify a subscript range for the array elements. You can use the Declare Array method to set the subscript range. You can write code that sets the number of elements in a dynamic array according to other conditions that your code specifies. For example, you might use an array to store a set of values that the user enters, but you might not know in advance how many values the user will enter. In this situation, you can do one of the following:

  • Dimension the array without specifying a subscript range, and then run a Declare Array method each time the user enters a new value.

  • Write code that prompts the user to enter the number of values, and then run one Declare Array method to set the size of the array.

If you use the Declare Array method to modify the size of an array, and if you must preserve the contents of this array, then make sure you include the following Preserve argument in the Declare Array method:

Redim Preserve ArrayName(n)

If you use a Declare Variable statement to declare a dynamic array, then it can include no more than eight dimensions. You must use the Declare Array method to create a dynamic array that includes more than eight dimensions. This method allows you to declare an array that includes up to 60 dimensions. For more information, see Declare Variable Statement and Declare Array Method.

You cannot use the Declare Array method to modify the number of dimensions of a dynamic array if the array already has dimensions. It can modify only the upper and lower boundaries of the dimensions of the array. For information about methods that can determine the current boundaries of an array, see Get Array Lower Boundary Method and Get Array Upper Boundary Method.

Example of a Dynamic Array

The following example code uses a dynamic array named varray to hold the cash flow values that the user enters:

Sub main
   Dim aprate as Single
   Dim varray() as Double
   Dim cflowper as Integer
   Dim msgtext as String
   Dim x as Integer
   Dim netpv as Double
   cflowper=2
   ReDim varray(cflowper)
   For x= 1 to cflowper
   varray(x)=500
   Next x
   aprate=10
   If aprate>1 then
      aprate=aprate/100
   End If
   netpv=NPV(aprate,varray())
   msgtext="The net present value is: "
   msgtext=msgtext & Format(netpv, "Currency")
   TheApplication.raiseErrorText msgtext
End Sub