The following code gives me error 9 \"subscript out of range\". I meant to declare a dynamic array so that the dimension changes as I add elements to it. Do I have to create
In addition to Cody's useful comments it is worth noting that at times you won't know how big your array should be. The two options in this situation are
Redim Preserve
The code below provides an example of a routine that will dimension myArray
in line with the lngSize
variable, then add additional elements (equal to the initial array size) by use of a Mod
test whenever the upper bound is about to be exceeded
Option Base 1
Sub ArraySample()
Dim myArray() As String
Dim lngCnt As Long
Dim lngSize As Long
lngSize = 10
ReDim myArray(1 To lngSize)
For lngCnt = 1 To lngSize*5
If lngCnt Mod lngSize = 0 Then ReDim Preserve myArray(1 To UBound(myArray) + lngSize)
myArray(lngCnt) = "I am record number " & lngCnt
Next
End Sub