VBA course · Lesson 9 of 33
For loops: For...Next and For Each
Repeat actions with For...Next and For Each: counters, Step, looping backwards to delete rows, looping through cells and sheets, Exit For and nested loops.
The real power of a macro shows when it does the same job many times: format 500 rows, check 30 invoices, rename 12 sheets. Writing the same line 500 times is not an option. Instead you write it once and put it inside a loop, a block of code that repeats.
VBA has two families of loops. For loops, covered here, are used when you know how many times to repeat, or when you want to visit every item in a collection such as every cell in a range or every sheet in a workbook. Do loops, covered in Do loops: Do While, Do Until and Exit Do, repeat until a condition changes and are useful when you do not know the count in advance.
For...Next with a counter
A For...Next loop uses a counter variable that starts at one number, goes up by one each time, and stops after it reaches the end number.
Option Explicit
Sub NumberRows()
Dim i As Long
For i = 1 To 10
Cells(i, 1).Value = i
Next i
End SubHere is what happens step by step:
- VBA sets
ito 1 and checks that 1 is not beyond 10. - It runs the body:
Cells(1, 1)(cell A1) gets the value 1. - At
Next iit adds 1 toiand jumps back to the top. - This repeats until
ibecomes 11, which is past the end, so the loop finishes and the code continues afterNext i.
Declare loop counters As Long, not As Integer. An Integer can only hold up to 32,767, and a worksheet has over a million rows; Long avoids an overflow error and is just as fast. Writing the variable name after Next is optional, but it makes nested loops much easier to read, so do it.
Using the counter as a row number
The most common pattern in Excel VBA is a loop over row numbers combined with Cells(row, column), which you met in Range and Cells: working with cells in VBA. This macro calculates a VAT amount and a total for each line of an invoice list:
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Invoice | Net | VAT | Total |
| 2 | INV-1001 | 1200 | ||
| 3 | INV-1002 | 450 | ||
| 4 | INV-1003 | 980 | ||
| 5 | INV-1004 | 2300 |
Before: net amounts only
Option Explicit
Sub AddVat()
Const VAT_RATE As Double = 0.2
Dim r As Long
For r = 2 To 5
Cells(r, 3).Value = Cells(r, 2).Value * VAT_RATE ' column C = VAT
Cells(r, 4).Value = Cells(r, 2).Value + Cells(r, 3).Value ' column D = total
Next r
End Sub| A | B | C | D | |
|---|---|---|---|---|
| 1 | Invoice | Net | VAT | Total |
| 2 | INV-1001 | 1200 | 240 | 1440 |
| 3 | INV-1002 | 450 | 90 | 540 |
| 4 | INV-1003 | 980 | 196 | 1176 |
| 5 | INV-1004 | 2300 | 460 | 2760 |
After running AddVat
The loop starts at row 2 to skip the header. Hard-coding the last row (5) is fine for practice, but real lists grow and shrink. In Find the last row and build dynamic ranges in VBA you will learn to find the last row automatically, which usually looks like this: lastRow = Cells(Rows.Count, "A").End(xlUp).Row followed by For r = 2 To lastRow.
Step: counting in jumps or backwards
By default the counter increases by 1. The Step keyword changes that. Step 2 visits every second number, which is useful for shading alternate rows:
Option Explicit
Sub BandRows()
Dim r As Long
For r = 2 To 21 Step 2
Rows(r).Interior.Color = RGB(242, 242, 242)
Next r
End SubA negative step counts down: For r = 20 To 2 Step -1. That sounds like a curiosity, but it is essential when you delete rows.
Why you must loop backwards when deleting
Imagine rows 3 and 4 both need to be deleted, and you loop forwards. At r = 3 you delete row 3. Everything below moves up one row, so the old row 4 is now row 3. The loop moves on to r = 4 and never looks at the row that slid into position 3. One of the rows you wanted to delete survives.
Looping from the bottom up avoids this, because deleting a row only shifts the rows below it, which you have already checked.
Option Explicit
Sub DeleteCancelled()
Dim lastRow As Long
Dim r As Long
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
For r = lastRow To 2 Step -1
If Cells(r, "D").Value = "Cancelled" Then
Rows(r).Delete
End If
Next r
End Sub| A | B | C | D | |
|---|---|---|---|---|
| 1 | Order | Customer | Amount | Status |
| 2 | SO-501 | Baker Ltd | 320 | Shipped |
| 3 | SO-502 | Cole & Co | 150 | Cancelled |
| 4 | SO-503 | Diaz SA | 870 | Cancelled |
| 5 | SO-504 | Evans plc | 410 | Shipped |
Before DeleteCancelled: two neighbouring rows are cancelled
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Order | Customer | Amount | Status |
| 2 | SO-501 | Baker Ltd | 320 | Shipped |
| 3 | SO-504 | Evans plc | 410 | Shipped |
After: both cancelled orders are gone
For Each: visiting every item in a collection
Excel is full of collections: the cells in a range, the worksheets in a workbook, the workbooks that are open. For Each visits every item in a collection without you having to count anything.
Option Explicit
Sub HighlightHighSales()
Dim cell As Range
For Each cell In Range("C2:C50")
If IsNumeric(cell.Value) And Not IsEmpty(cell.Value) Then
If cell.Value > 10000 Then
cell.Interior.Color = RGB(198, 239, 206)
End If
End If
Next cell
End SubThe loop variable cell must be declared as an object that matches what the collection contains: Range for cells, Worksheet for sheets, Workbook for workbooks. On each pass, cell is the current cell, so you can use all its properties directly. For a multi-column range, For Each goes across each row first, then down to the next row.
Looping through sheets works the same way:
Option Explicit
Sub ListSheets()
Dim ws As Worksheet
Dim indexSheet As Worksheet
Dim r As Long
Set indexSheet = Worksheets.Add(Before:=Worksheets(1))
indexSheet.Name = "Index"
indexSheet.Range("A1").Value = "Sheet name"
r = 2
For Each ws In ThisWorkbook.Worksheets
If ws.Name <> indexSheet.Name Then
indexSheet.Cells(r, 1).Value = ws.Name
r = r + 1
End If
Next ws
End SubHere a separate counter r keeps track of the next free row, because For Each does not give you a number. (If a sheet called Index already exists, renaming the new one fails; Error handling and debugging in VBA shows how to deal with that gracefully.)
For Each when you want every item and do not care about the position. Use For...Next with a counter when you need the row number, want to skip rows, or need to go backwards. Never delete rows inside a For Each over the same range: the range changes under the loop and rows get skipped.Leaving early with Exit For
Sometimes you are searching for something and can stop as soon as you find it. Exit For jumps out of the loop immediately and continues after Next.
Option Explicit
Sub FindFirstUnpaid()
Dim r As Long
Dim found As Boolean
For r = 2 To 500
If Cells(r, "E").Value = "Unpaid" Then
found = True
Exit For
End If
Next r
If found Then
MsgBox "First unpaid invoice is in row " & r & ": " & Cells(r, "A").Value
Else
MsgBox "All invoices are paid."
End If
End SubAfter Exit For, the counter keeps the value it had when the loop stopped, so r tells you where the match is. For large searches, Range.Find is faster still; see Find, filter and sort data with VBA.
Nested loops
A loop can contain another loop. The inner loop runs completely for every single pass of the outer loop. This builds a small multiplication table in B2:K11:
Option Explicit
Sub TimesTable()
Dim r As Long
Dim c As Long
For r = 1 To 10
For c = 1 To 10
Cells(r + 1, c + 1).Value = r * c
Next c
Next r
End SubThat is 100 cell writes. Nested loops multiply quickly: 1,000 rows by 50 columns is 50,000 iterations, and writing to cells one by one gets slow. For big jobs read the data into an array, loop over the array and write it back in one go; Arrays in VBA: static, dynamic and fast range processing and Make your macros fast: speed optimization in VBA explain how.
Common mistakes
- Changing the counter inside the loop: writing
r = r + 1inside aFor rloop makes it skip rows. LetNextdo the counting. - Deleting rows going forwards: always loop with
Step -1when deleting. - Wrong
Nextvariable: in nested loops,Next rplaced whereNext cbelongs causes "Invalid Next control variable reference". - Mixing up
Set: theFor Eachloop assigns its object variable for you, but any other object variable needsSet, as inSet indexSheet = Worksheets.Add. Leaving it out gives "Object variable or With block variable not set". - Looping through a whole column:
For Each cell In Range("A:A")visits over a million cells. Limit the range to the used rows. - Using
Integercounters: overflow above 32,767. UseLong.
Check yourself
1. What values does r take in For r = 2 To 10 Step 3?
The counter starts at 2 and adds 3 each time; 11 is beyond the end value, so the loop stops after 8.
2. Why should a loop that deletes rows run from the bottom up?
Looping backwards means deleted rows only affect rows that have already been checked.
3. Which variable type should the loop variable have in For Each ws In ThisWorkbook.Worksheets?
For Each needs an object variable matching the items in the collection.
4. What does Exit For do?
VBA has no "continue" statement; Exit For jumps out of the loop entirely.
5. An outer loop runs 20 times and the inner loop runs 5 times. How often does the inner body run?
The inner loop runs completely on every outer pass: 20 x 5 = 100.