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 a "spot" on the array before I store something in it like in JS?
Sub test_array() Dim test() As Integer Dim i As Integer For i = 0 To 3 test(i) = 3 + i Next i End Sub
Add a New Value to an Array in VBA First, you need to use the “ReDim” statement with the “Preserve” keyword to preserve the two elements including the new element for which you want to add the value. Next, you need to define the elements that you want to have in the array.
Redim Statement is used to re-define the size of an Array. When the array is declared without any size, then it can be declared again using Redim with the feasibility of specifying the size of an array. Preserve keyword is used to preserve the contents of a current array when the size of an array gets changed.
in your for loop use a Redim on the array like here:
For i = 0 to 3 ReDim Preserve test(i) test(i) = 3 + i Next i
As Cody and Brett mentioned, you could reduce VBA slowdown with sensible use of Redim Preserve
. Brett suggested Mod
to do this.
You can also use a user defined Type
and Sub
to do this. Consider my code below:
Public Type dsIntArrayType eElems() As Integer eSize As Integer End Type Public Sub PushBackIntArray( _ ByRef dsIntArray As dsIntArrayType, _ ByVal intValue As Integer) With dsIntArray If UBound(.eElems) < (.eSize + 1) Then ReDim Preserve .eElems(.eSize * 2 + 1) End If .eSize = .eSize + 1 .eElems(.eSize) = intValue End With End Sub
This calls ReDim Preserve
only when the size has doubled. The member variable eSize
keeps track of the actual data size of eElems
. This approach has helped me improve performance when final array length is not known until run time.
Hope this helps others too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With