Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating VBA dynamic arrays

Tags:

arrays

vba

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 
like image 297
sebastien leblanc Avatar asked Jan 13 '12 13:01

sebastien leblanc


People also ask

How do I add data to an array in VBA?

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.

What is the difference between ReDim and ReDim preserve?

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.


2 Answers

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 
like image 171
Fluffi1974 Avatar answered Sep 16 '22 15:09

Fluffi1974


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.

like image 21
a505999 Avatar answered Sep 19 '22 15:09

a505999