VBA For Next loop: work through a list row by row
A loop repeats statements until a counter reaches its end value. That is how a macro handles a whole list instead of a single row: fill in line totals, add up amounts, check values. For Next is the loop you will use most in Excel.
In short: For i = 2 To 8 … Next i runs the lines in between once for each value of i: 2, 3, 4 and so on up to 8. Inside the loop, Cells(i, 4) points to the current row.
What you need to know: Range and Cells, variables and If Then Else from level 1.
Try it right now
Seven items, and column D is missing the line total for each. Instead of seven lines of code, you write a loop with a single calculation inside.
Task Write a macro LineTotals that fills column D with quantity times unit price for rows 2 to 8. Use a For Next loop with the counter i. Check also tests it with other quantities.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Item | Qty | Unit price | Total |
| 2 | Copy paper A4 | 10 | 4.95 | |
| 3 | Lever arch file | 25 | 2.49 | |
| 4 | Ballpoint pens, blue | 50 | 0.89 | |
| 5 | Sticky notes | 12 | 1.79 | |
| 6 | Black toner | 2 | 64.90 | |
| 7 | Clear pockets | 5 | 3.20 | |
| 8 | Staples | 8 | 1.15 |
How For Next works
Sub LineTotals()
Dim i As Long
For i = 2 To 8
Cells(i, 4).Value = Cells(i, 2).Value * Cells(i, 3).Value
Next i
End Sub
| Part | Meaning |
|---|---|
Dim i As Long | The counter. Long rather than Integer, because Integer stops at 32,767 and sheets can be longer than that. |
For i = 2 To 8 | Start value 2, end value 8. VBA sets i to 2 and checks whether it is already past 8. |
Cells(i, 4) | The cell in the current row, column 4 (D). D2 on the first pass, then D3, and so on. |
Next i | Adds 1 to i and jumps back to For. Once i is greater than 8, the macro carries on after Next. |
The lines between For and Next are the body of the loop. Indent them so it is obvious what gets repeated. You can leave out the name after Next, but with nested loops it tells you which Next closes which For.
One detail: after the loop, i is 9, not 8. Next added 1 one last time before the loop ended. Keep that in mind if you use the variable afterwards.
Loop to the last row, not to 8
A fixed number like 8 only works while the list stays exactly that long. Add a row next week and the macro silently skips it. So you find the last used row before the loop starts:
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lastRow
total = total + Cells(i, 3).Value
Next i
Range("F2").Value = total
Cells(Rows.Count, 1) is the bottom cell of column A, .End(xlUp) jumps up from there to the first cell with data, and .Row returns its row number. The next lesson, find the last row, explains this in detail along with the alternatives. For this exercise, the one line is all you need.
The total uses a pattern you will need again and again: a variable starts at 0, and every pass adds the current value to it. The result is only complete after Next.
One more exercise: a total over all rows
Check runs this one on more invoices than you can see. A loop with a fixed end value will fail.
Task The macro AddUp should add up all amounts in column C and write the total to F2. The list grows every week, so find the last row with Cells(Rows.Count, 1).End(xlUp).Row and run the loop down to it. Check tests with more invoices.
| A | B | C | D | E | F | |
|---|---|---|---|---|---|---|
| 1 | Invoice | Customer | Amount | |||
| 2 | R-1041 | Carter Bakery | 1,250.00 | Total | ||
| 3 | R-1042 | Peters Motors | 3,480.50 | |||
| 4 | R-1043 | Riverside Dental | 620.00 | |||
| 5 | R-1044 | Green Leaf Garden Centre | 945.80 | |||
| 6 | R-1045 | Hotel Marlow | 2,150.00 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Step: count in other increments
By default, For counts up by one. Step sets a different increment:
| Loop | Values of i | Typical use |
|---|---|---|
For i = 2 To 10 Step 2 | 2, 4, 6, 8, 10 | every other row, for example a list with a blank row after each entry |
For i = lastRow To 2 Step -1 | bottom to top | deleting rows without skipping the row that moves up |
Counting backwards is the standard way to delete rows. The reason is covered in delete rows in level 4.
Exit For leaves the loop early, usually inside an If: once you have found what you were looking for, there is no need to go through the rest of the list.
Find the bug
This macro stops on the very first pass. The message alone does not tell you why. Look at the value of the counter at that moment.
Task Find the bug: the macro SalePrices should write the price after a 10% discount into column C (list price times 0.9), but it stops with "Run-time error '13': Type mismatch". Get it running.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Item | List price | Sale price | |
| 2 | Desk lamp | 39.90 | ||
| 3 | Comfort office chair | 249.00 | ||
| 4 | Monitor arm | 59.50 | ||
| 5 | Footrest | 24.90 | ||
| 6 | Letter tray | 12.80 | ||
| 7 | ||||
| 8 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Common mistakes
Starting the loop at the heading
With For i = 1 To lastRow, the macro also calculates with row 1, which holds text. The exercise then reports "Run-time error '13': Type mismatch". Data almost always starts in row 2.
Forgetting Next
Without Next, VBA stops before the macro even runs: "Compile error: For without Next". With several loops, clean indentation helps: every For sits directly above its Next.
Wrong name after Next
For i = 2 To lastRow followed by Next j gives "Compile error: Invalid Next control variable reference". The name after Next must match the counter of its For.
A fixed end value
For i = 2 To 6 is only right for this exact list. The exercise tells you: "It works on the visible data but not when checked with more or fewer rows. The loop stops at a fixed number". In real Excel this is the worse case, because there is no message at all; rows are simply missing.
Overwriting the total instead of adding
total = Cells(i, 3).Value replaces the total with the current amount on every pass, so you end up with the last amount only. It has to be total = total + ….
In real Excel
Loops make most sense when you step through them: put the cursor in the macro and press F8. Each press runs one line. Hover over i and the editor shows its current value. In the exercises here, use Step through; the Locals window shows every variable as you go. More in Debugging.
A macro that writes thousands of cells one by one can take a few seconds in real Excel. For everyday office lists, a For loop is fast enough. Ways to speed up large jobs come in levels 4 and 5.
FAQ
Does the counter have to be called i?
No, you can pick any name. i, j and r are common. A descriptive name such as rowNum helps once a second loop over columns comes into play.
What is the difference between For Next and For Each?
For Next counts a number up, and you use it as the row number. For Each goes through every cell in a range directly, with no counter. Both are fine; For Next is handier when you need several columns from the same row.
Can I change the counter inside the loop?
VBA lets you, but the code becomes hard to follow and easily ends up on the wrong row. If you want to leave the loop early, use Exit For.
What happens if the start value is bigger than the end value?
The loop does not run at all. That happens, for instance, when the list is empty and lastRow is 1: For i = 2 To 1 skips the body without an error.
Every loop compared, with a table of which one fits when: VBA loops overview.