16

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?

3 Answers 3

32

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.

Sign up to request clarification or add additional context in comments.

Comments

1
Private Sub ArrayMy(DataRange)
  Dim DataIndex() As String
  i = 0
  On Error Resume Next
  ReDim DataIndex(0)
  For Each c In DataRange
      DataIndex(i) = c
      i = i + 1
      ReDim Preserve DataIndex(i)
  Next
End Sub

Comments

1

I think is better to use the listArray object:

Dim list, name as variant
Set list = CreateObject("System.Collections.Arraylist")

For i = 1 to Last then  ''Loop in the range
    If strName = "Henry" then
        list.Add ValueToAdd  ''add to the list
    End if 
Next

and then you can loop in the list

For Each name in List
    Msgbox name
Next

1 Comment

Late to the party here, but have you actually tried to run this code? In a VBA environment? There are quite a few errors that prevent it from even compiling.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.