Skip to content

Repeat steps for every row with For and For Each

Write VBA9 minPremium

Builds on Make decisions with If and Select Case and Point at cells with Range, Cells, Offset and CurrentRegion.

A property manager in Porto checks 140 rent payments at the start of every month and marks each tenant who paid less than the rent. The company keeps taking on buildings, so the list grows, and the macro can't stop at a fixed row.

How it works

For...Next counts. For r = 2 To lastRow runs the lines down to Next r with r set to 2, then 3, and so on to lastRow. Inside the loop, Cells(r, 4) is column D on row r, so each pass works on the next row.

To find the last row, start at the bottom of the sheet and jump up to the last filled cell, the way CtrlUp does: Cells(Rows.Count, 1).End(xlUp).Row. Rows.Count is the sheet's last row, 1,048,576.

VBA
Sub MarkShortPayments()
Dim r As Long, lastRow As Long
lastRow = Cells(Rows.Count, 1).End(xlUp).Row
For r = 2 To lastRow
If Cells(r, 4).Value < Cells(r, 3).Value Then
Cells(r, 5).Value = "Short"
End If
Next r
End Sub
Marks Short in column E for each tenant who paid less than the rent, from row 2 to the last row with a tenant.

For Each walks the cells of a range one at a time, so you don't need the row number. In For Each cell In Range("D2:D6"), cell is D2 on the first pass, then D3, down to D6.

  1. Step 1: On the first pass, cell is D2, and the lines inside the loop run once.
  2. Step 2: Next cell moves cell down to D3, and the lines run again.
  3. Step 3: After D6 the range has no more cells, so the loop ends.
For Each cell In Range("D2:D6") gives cell to D2, then D3, and so on. After the last cell, the macro carries on after Next cell.

Common mistakes

  • For r = 2 To 140. Next month's new tenants are left out; find lastRow instead.
  • Range("A1").End(xlDown).Row stops above the first empty cell in column A, so a blank row in the list cuts the loop short. Count up from the bottom with End(xlUp).
  • Deleting rows in a loop that counts up. When row 5 goes, row 6 moves into its place and the loop moves on to row 6, skipping it. Count down instead: For r = lastRow To 2 Step -1.

In short

  • For r = 2 To lastRow ... Next r repeats lines for every row, with r as the row number.
  • Cells(Rows.Count, 1).End(xlUp).Row finds the last filled row of column A.
  • For Each cell In a range walks its cells one at a time; delete rows from the bottom up.

Practice

Premium

4 exercises: 3 macros and 1 quiz question.

Practice is part of Premium

Every lesson is free to read, and you can practice the free lessons without an account. This lesson's exercises are part of Premium, which you add to a free account.