Search code examples
arraysexcelvbaloops

How to loop through an array?


How do I loop through an array? The idea is to go to the Names worksheet, Where I have a list of users Initials and names in a list. Create 2 arrays that record the initial and name of each person. Then count how many people are in the sheet. (I believe the count is needed to end the loop? where the initial is entered every 3 rows, Ive specified 3 times the total count) Next is go to the 'LoopTest' worksheet and enter the initial, plus add in Sex and Age.

So as per below, as far as I've got is to try to enter the Initial, then the next line record Sex, then Age. Then loops back on to the next initial (after 3 lines). I'm trying to add 1 to the array for every loop so that it prints out the initials in order. However there is an error that occurs when calling the array - Initial(i).

Would anyone be able to see my errors?

Sub LoopTEST2()

Worksheets("Names").Activate

Dim Initial(1 To 18) As String
Dim Names(1 To 18) As String
    
    Initial(1) = Range("A2").Value
    Initial(2) = Range("A3").Value
    Initial(3) = Range("A4").Value
    
    Names(1) = Range("B2").Value
    Names(2) = Range("B3").Value
    Names(3) = Range("B4").Value

NumRows = Range("A2", Range("A2").End(xlDown)).Rows.Count


Worksheets("LoopTest").Activate

Dim i As Integer
    For i = 1 To NumRows * 3 Step 3
    Cells(i, 1).Value = Initial(i): Cells(i + 1, 1).Value = "Sex:": Cells(i + 2, 1).Value = "Age:":
    
Next i
End Sub

Solution

  • The control variable i in the loop changes with step 3, and you need to read consecutive elements from the Initial array. So either use a different variable or calculate the index of the Initial array each time.
    Either

    Dim i As Integer, j As Integer
    For i = 1 To NumRows * 3 Step 3
        j = j + 1
        Cells(i, 1).Value = Initial(j)
        Cells(i + 1, 1).Value = "Sex:"
        Cells(i + 2, 1).Value = "Age:" 
    Next i
    

    Or

    Dim i As Integer
    For i = 1 To NumRows * 3 Step 3
        Cells(i, 1).Value = Initial(i \ 3 + 1)
        Cells(i + 1, 1).Value = "Sex:"
        Cells(i + 2, 1).Value = "Age:" 
    Next i