FormulaCamp
Completed
13. VBA and Macros · Language Basics · 25 min

3. VBA: Looping Over a Range

Lesson 3 of 7
Task 1 of 3
  1. In D2:D7, write what the macro writes: "Overdue" if the due date is earlier than the date in F1, otherwise "On time".

Lesson theory

Three loops handle most tasks:

  • For r = 2 To lastRow … Next r goes by row numbers, when you need to reach different columns of the same row through Cells(r, n). Step 2 steps by 2, and Step -1 runs backward;
  • For Each cell In Range("B2:B100") … Next cell goes through each cell of a range;
  • Do While condition … Loop repeats while the condition is true, for example while a cell is not empty. Don't forget to increase the counter, or the loop never ends.

The last filled row: lastRow = Cells(Rows.Count, 1).End(xlUp).Row. It's like pressing Ctrl+↑ from the very bottom of column A. Exit For leaves the loop early. If the loop deletes rows, go from the bottom up (Step -1), or the rows will shift and some will be skipped.

Sub InvoiceStatus()
    Dim r As Long, lastRow As Long, cnt As Long
    Dim total As Double
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    For r = 2 To lastRow
        If Cells(r, 3).Value < Range("F1").Value Then
            Cells(r, 4).Value = "Overdue"
            cnt = cnt + 1
            total = total + Cells(r, 2).Value
        Else
            Cells(r, 4).Value = "On time"
        End If
    Next r
    Range("F2").Value = cnt
    Range("F3").Value = total
End Sub

An invoice is overdue if its due date (column C) is earlier than the report date in F1. Reproduce the macro's result with formulas. A good habit: if one formula solves the task, you don't need a macro. A macro pays off when the action repeats every day on new files.

Speed: reading cells one at a time is slow. For thousands of rows, load the range into an array (arr = Range("A2:C5000").Value), process it in memory, and write it back in one go. While the macro runs, turn off screen redrawing: Application.ScreenUpdating = False.

The simulator doesn't run macros or scripts. Run the code from the lesson in desktop Excel (VBA) or in Excel for the web (Office Scripts). Here you learn to read code and check yourself with formulas and a quiz.

Test yourself

1. How many times does the loop body run: For i = 1 To 10 Step 3 … Next i ?
2. Which cell does Cells(3, 2) refer to?
3. A macro deletes blank rows with a For r = 2 To lastRow loop and Rows(r).Delete, but some blank rows remain. How do you fix it?
4. Code: r = 2: Do While Cells(r, 1).Value <> "": Cells(r, 2).Value = 1: Loop. What is wrong?
5. What does Cells(Rows.Count, 1).End(xlUp).Row return if A1:A57 is filled in column A?
6. Which cell does Range("A1").Offset(1, 2) refer to?
7. A loop over 50,000 rows with Cells takes a minute. What speeds it up the most?

Practice is part of Pro

The live spreadsheet, task checking and .xlsx files in all 170 lessons. Your progress is saved in this browser; sync across devices is coming soon.