Excel VBA Loop Syntax: For, Do, and Each Explained

VBA & macros · Updated November 21, 2026

Excel VBA loops repeat a block of code: use For...Next for a known number of repetitions, For Each...Next to visit every item in a range or collection, and Do...Loop when repetition depends on a condition. Choose the loop that makes its stopping rule clearest, and make sure every conditional loop can eventually stop.

What a VBA loop does

A loop runs one or more statements repeatedly while a counter or condition directs it to continue. In Excel, loops are useful for processing rows, checking cells, updating worksheets, and applying the same operation to many workbook objects. The loop itself does not make a task safer or faster: its result depends on the statements inside it, the range or collection it visits, and the condition that ends it.

Most loops have three parts: a starting point, the work to repeat, and a rule that ends repetition. A counted loop states its start and finish directly. A condition-based loop tests a condition before or after its repeated statements. Understanding that difference helps prevent skipped work and infinite loops.

For…Next syntax for a known count

Use For...Next when you know the number of passes or can calculate it before starting. Its general syntax is:

For counter = start To end [Step increment]
    statements
Next counter

The brackets indicate an optional part of the syntax; do not type the brackets themselves. The increment defaults to 1. This complete procedure prints the numbers 1 through 5 in the Immediate window:

Sub CountToFive()
    Dim i As Long

    ' Visit each number from 1 through 5.
    For i = 1 To 5
        Debug.Print i
    Next i
End Sub

In the VBA editor, the Immediate window can display output from Debug.Print. The counter is a Long, the usual choice for row numbers and loop counters in Excel. An older Integer variable can hold only values from -32,768 to 32,767, which is too small for many worksheet row counts.

Use Step to change how the counter advances. For example, For i = 2 To 10 Step 2 visits 2, 4, 6, 8, and 10. A negative step counts downward: For i = 10 To 1 Step -1 visits 10 down to 1. The step must point toward the end value; otherwise, the loop may not run. A For loop with a counter that reaches its end normally finishes after the final pass.

For Each…Next for ranges and collections

Use For Each...Next when the task is to process every member of a collection, rather than calculate a numeric sequence. A range is a collection of cells, and a workbook also has collections such as its worksheets. This example visits each cell in a fixed range without calculating row numbers:

Sub InspectCells()
    Dim ws As Worksheet
    Dim cell As Range

    ' Set the worksheet that contains the target range.
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    For Each cell In ws.Range("A1:A10")
        Debug.Print cell.Address(False, False), cell.Value
    Next cell
End Sub

The variable in a For Each loop must be an appropriate object type or a Variant. Here, cell is declared as a Range, so its properties, such as Address and Value, are available. Replace Sheet1 with the actual worksheet name in the workbook. ThisWorkbook means the workbook containing the VBA code; it is different from ActiveWorkbook, which refers to the workbook currently active in Excel.

For Each is often easier to read than a numeric loop when you do not need the item’s position. If you need to use a row number, compare neighboring cells, or move through a range in reverse, a For...Next loop may be more suitable. Do not change the collection being traversed in ways that invalidate its iteration; deleting worksheets while looping through the same worksheets collection, for example, needs additional care.

Do…Loop for condition-based repetition

Use Do...Loop when the number of passes is not known in advance and a condition controls whether the loop continues. A condition before the work can prevent the body from running at all. This example reads values in column A until it reaches an empty cell:

Sub ReadUntilBlank()
    Dim ws As Worksheet
    Dim r As Long

    ' Read from the named worksheet, starting at row 2.
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    r = 2

    Do While Len(ws.Cells(r, 1).Value) > 0
        Debug.Print ws.Cells(r, 1).Value
        r = r + 1
    Loop
End Sub

Do While condition keeps repeating while the condition is true. The alternative Do Until condition keeps repeating until the condition becomes true. Both forms can test at the beginning, as in Do While condition ... Loop, or at the end, as in Do ... Loop While condition. A condition tested at the end is checked only after the body runs, so that version always executes the body at least once.

In the example, the value in column A must be filled continuously from row 2 down to the first blank. If the data has gaps, the loop stops at the first gap and will not inspect later rows. When the last row is known, a counted For...Next loop is usually clearer. When there may be gaps or the stopping point depends on a changing value, decide deliberately whether the test belongs before or after the work.

Choosing the right loop

Choose based on what controls the repetition, not on which syntax looks shortest. A useful rule of thumb is:

  • Use For...Next for a fixed count, a row-number range, or a sequence that needs a specific step.
  • Use For Each...Next to visit every cell, worksheet, or other collection member without needing a numeric index.
  • Use Do...Loop when a condition determines when to stop, particularly when the number of iterations is not known beforehand.

For example, if a report has data from row 2 through a known last row, a counter loop communicates the bounds. If the task is to inspect all worksheets and check a property of each, a collection loop communicates that intent. If a process should keep asking or checking until a particular condition changes, a Do loop expresses the condition directly. Avoid choosing a condition-based loop merely to imitate a counted loop; explicit bounds are easier to review.

Example: process worksheet rows safely

A common Excel task is to delete rows whose column A value is blank. Deleting while counting upward can skip rows: after a row is removed, the next row moves into its place, but the counter advances. Counting downward avoids that shift problem. This example checks rows 2 through the last used cell in column A and deletes blank entries:

Sub DeleteBlankEntries()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim r As Long

    ' Work on the intended worksheet.
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    ' Move upward so deleting a row does not skip the next one.
    For r = lastRow To 2 Step -1
        If Len(ws.Cells(r, "A").Value) = 0 Then
            ws.Rows(r).Delete
        End If
    Next r
End Sub

This assumes row 1 is a header and column A determines whether a record is blank. It does not delete a row merely because some other column is empty. The End(xlUp) approach finds the last nonempty cell in column A; if that column is empty below the header, the procedure will not inspect other columns to find records. Adapt both the test and the last-row calculation to the actual layout before running it.

Save a copy of the workbook before running any macro that changes or deletes data. VBA changes cannot be undone with Ctrl+Z, so a backup is the practical way to recover from an unintended result.

Nested loops and early exits

A loop can contain another loop. This is called nesting and is useful for comparing combinations, such as every row against every column in a small defined area. The inner loop completes its passes for each pass of the outer loop. If the outer loop has 100 passes and the inner loop has 20, the statements inside the inner loop can run 2,000 times. That multiplication matters when the repeated work is substantial.

Exit For leaves the nearest enclosing For loop. In nested loops, it exits only the inner loop, not both loops. VBA does not have a native Continue For statement; to skip work for one item, put the work inside an If block that checks whether the item should be processed. This keeps the loop’s progression and exit rule visible.

Common loop errors and fixes

An infinite loop is the most disruptive mistake in a condition-based loop. It happens when the condition never becomes false or true as required. In the earlier example, forgetting r = r + 1 would repeatedly inspect the same cell. Check that every path through the loop updates the value that controls its condition, and consider adding a limit or a clearly defined exit condition when the data may be malformed.

Other frequent problems include:

  • Wrong bounds: A loop from row 1 may process a header, while a loop ending one row too early leaves out the final record. State whether the first or last row is included.
  • Wrong direction: Deleting rows while counting upward can skip records. Count down when removing items from a worksheet range.
  • Unqualified references: Using Cells or Range without a worksheet qualifier can target whichever sheet is active. Use ws.Cells or ws.Range when the intended sheet is known.
  • Unexpected blank or error values: A loop that stops at the first blank is not appropriate if blanks can occur between records. Error values may also require explicit handling before a value is treated as ordinary text or a number.

During debugging, use the VBA editor’s step-through controls and inspect the counter or condition after each pass. A temporary Debug.Print statement can show which row or value the loop reached. Remove or adjust diagnostic output when it is no longer needed.

Performance and workbook safety

A loop over a small range is generally straightforward, but repeated worksheet reads and writes can become slow for large datasets because each access crosses between VBA and Excel’s worksheet object model. For large jobs, a common approach is to read a range into a VBA array, process values in memory, and write results back in a block. That technique requires careful handling of the array dimensions and the range’s size; it is not necessary for every macro.

Avoid using Select and Activate just to reach cells in a loop. Referencing a worksheet and its cells directly is clearer and avoids relying on the user’s active sheet. Also check that the intended workbook and sheet exist before running a procedure that changes data. A macro that refers to a misspelled sheet name will raise an error rather than silently find a different sheet.

VBA macros run in the desktop Excel application, not in Excel for the web. On Windows, open the VBA editor with Alt+F11; Mac keyboard shortcuts can vary with the keyboard and system settings, so use Excel for Mac’s Tools or Developer menu to open the Visual Basic Editor if needed. Do not enable or run a macro from an untrusted workbook just because it contains a useful-looking loop.

Frequently Asked Questions

What is the basic loop syntax in Excel VBA?

The basic counted form is For counter = start To end, followed by the statements to repeat and then Next counter. For a condition-based loop, use Do While condition or Do Until condition, followed by the repeated statements and Loop.

What is the difference between For Next and For Each in VBA?

For...Next advances a numeric counter through a sequence. For Each...Next visits each item in a collection, such as every cell in a range. Use the first when the index or step matters and the second when you simply need to process each member.

How do I loop through rows in Excel VBA?

Use a For...Next counter from the first data row to the last data row, and refer to cells through a worksheet variable such as ws.Cells(r, 1). Calculate or set the last row to match the column and layout that define your data.

How do I stop a VBA loop?

A counted For loop ends when it reaches its end value. A Do loop ends when its condition changes so the loop should stop. Exit For can leave a For loop early; for a Do loop, use Exit Do. Make sure an early exit is intentional and does not leave partially processed data.

Can Excel for the web run VBA loops?

No. Excel for the web can open and edit many macro-enabled workbooks, but it cannot create, run, or edit VBA macros. Use the desktop version of Excel for VBA, and save a copy before running a macro that changes workbook contents.

Related

Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.

More in VBA & macros

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.