Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding values to variable array VBA

I am trying to loop through a table that has a column for "customers" and "dollar amount". If my loop finds a customer called "greg" or "henry" I want to add his "dollar amount" to an array of an unknown size.

Can someone please help me?

like image 272
Trung Tran Avatar asked Sep 30 '12 18:09

Trung Tran


People also ask

How do you add values to an array in VBA?

VBA does not allow you to append items to an array. The standard method to work around this is to re-dimension to array to the required size and then add the required items. There are a number of problems with this method: Performance – The array is copied into a new array each time it is re-dimensioned.

How do I fill an array in Excel VBA?

To Fill a Dynamic ArrayOn the Tools menu, point to Macro and then click Macros. In the Macro dialog box, click fill_array, and then click Run.

How do I add a row to an array in VBA?

In VBA you cannot append an item to an array. Instead you must re-dimension the array to be one index larger than the previous. You cannot check the Ubound (upper bounds) of an array if it does not have a dimension.

How do I add items to a list in VBA?

There are 3 ways to add items to the VBA Listbox: One at a time using the AddItem property. Adding an array/range using the List property. Adding a Range using the RowSource property.


1 Answers

If by unknown size, you mean that number of elements is unknown, you could use a dynamic array.

Dim aArray() As Single ' or whatever data type you wish to use
ReDim aArray(1 To 1) As Single
If strFirstName = "henry" Then
    aArray(UBound(aArray)) = 123.45
    ReDim Preserve aArray(1 To UBound(aArray) + 1) As Single
End If

Ubound(aArray) throws an error if the array hasn't been dimensioned, so we start by adding an element to it. That leaves us with an empty element at the end of the text, so your code should account for that. aArray(Ubound(aArray)-1) will give you the last valid element in the array.

like image 96
Steve Rindsberg Avatar answered Oct 07 '22 02:10

Steve Rindsberg