
📎 This article includes 1 downloadable practice file ↓
📘 Excel VBA Course · Lesson 6 of 15 — see all lessons
In this article
Loops let a macro repeat work: process every row, every sheet, every file. VBA has four kinds, and choosing the right one makes code simpler.
For…Next: a known number of times
Dim i As Long
For i = 2 To lastRow
Cells(i, "D").Value = Cells(i, "B").Value * Cells(i, "C").Value
Next i
Add Step to change the increment: For i = 10 To 1 Step -1 counts down (essential when deleting rows).
For Each: every item in a collection
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
ws.Range("A1").Font.Bold = True
Next ws
Dim c As Range
For Each c In Range("B2:B100")
If c.Value < 0 Then c.Font.Color = vbRed
Next c
Use For Each for sheets, workbooks, cells in a range or items in a collection — no counter needed.
Do While / Do Until: until a condition changes
Dim r As Long: r = 2
Do While Cells(r, 1).Value <> ""
' process row r
r = r + 1
Loop
Do Until Cells(r, 1).Value = "" ' same thing, opposite wording
r = r + 1
Loop
Step through a Do While loop in the VBA Playground and watch the running total build up.
r = r + 1 and the loop never ends. Press Esc or Ctrl+Break to stop a runaway macro — and save before testing loops.Leaving a loop early
For Each c In Range("A2:A1000")
If c.Value = "TOTAL" Then Exit For
Next c
Exit For and Exit Do jump straight past the loop. VBA has no “continue” keyword; use an If around the body instead.
Nested loops
For r = 1 To 12
For c = 1 To 12
Cells(r, c).Value = r * c ' a times table
Next c
Next r
Making loops fast
- Turn off screen updating:
Application.ScreenUpdating = False(lesson 13). - Read the range into an array, loop over the array, write back once (lesson 11).
- Avoid
.Selectand.Activateinside loops.
| Loop | Use when |
|---|---|
| For…Next | You know the start and end (row numbers) |
| For Each | You want every item in a collection |
| Do While / Until | You stop when something changes (blank cell, file not found) |
Try it yourself: step by step
- Run
L06_RunningTotal: column I fills with a running total using Do While. - Rewrite it as a
For r = 2 To lastRowloop — same result. - Add
If .Cells(r, "C").Value = "North" Thenso only North invoices are added. - Time it: put
t = Timerat the start andMsgBox Timer - tat the end, then addApplication.ScreenUpdating = Falseand compare. - Watch loops run line by line in the VBA Playground.
📎 Practice files for this article
- 📗Practice workbook with all course macros (.xlsm)Open it, click Enable Content in the yellow bar, go to the Macros sheet and press any button. 60 sales rows included to test on.⬇ XLSM · 29 KB
Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.