Excel VBA: How to Exit a For Next Loop Early in Your Macro

VBA & macros · Updated November 21, 2026

Yes. In Excel VBA, put Exit For inside a For...Next loop to leave it as soon as a condition is met; execution then continues with the statement after the loop. The loop’s Next line still belongs in the code, even though VBA skips to the code after it when it exits early.

What Exit For does

A For...Next loop repeats a block of statements for a sequence of values. For example, a counter might run from 1 to 100, or a procedure might inspect each cell in a range. Sometimes the macro finds what it needs before reaching the final iteration. Exit For provides a deliberate way to stop at that point instead of continuing through unnecessary iterations.

VBA evaluates the statements in the loop in order. When execution reaches Exit For, it leaves the current loop immediately. It does not resume at the next statement inside the loop, and it does not continue incrementing the loop counter. Execution picks up after the loop’s corresponding Next statement.

This is different from changing the loop’s counter or using a condition that happens to prevent further work. Exit For makes the reason for stopping explicit in the code, which is especially useful for searches and checks that should stop at the first match.

A basic For Next example

The following macro searches A1:A100 for the word STOP. It displays the address of the first matching cell and exits the loop immediately. If no cell contains STOP, the message reports that no match was found. Save a copy of the workbook before running a macro; VBA changes cannot be reversed with Ctrl+Z.

Sub FindStopValue()
    Dim cell As Range
    Dim found As Boolean

    found = False

    ' Search each cell and stop at the first match.
    For Each cell In Worksheets("Sheet1").Range("A1:A100")
        If cell.Value = "STOP" Then
            found = True
            MsgBox "Found at " & cell.Address
            Exit For
        End If
    Next cell

    If Not found Then
        MsgBox "No match found."
    End If
End Sub

Although this example uses For Each, it is still a VBA For loop, so Exit For is valid. The found variable distinguishes a successful search from a loop that simply reached its end. Without that check, a macro could finish without telling the user whether it found anything.

Choose the right stopping condition

Place Exit For in the branch that represents the reason to stop. A search commonly exits when a value matches; a validation loop may exit when it discovers an invalid entry. Be specific about the condition so that the macro does not stop on an unrelated blank or error value.

  • Stop on the first match: Compare the current value to the target, then exit when they are equal.
  • Stop on a boundary: Exit when a sentinel value, such as END, marks the end of meaningful data.
  • Stop on invalid data: Exit when the current record fails a required check, and record or report which record caused the stop.
  • Stop after a limit: Use a counter or the loop’s defined bounds when the goal is to process a fixed number of items. An early exit is not necessary if the loop already has the correct limit.

For example, suppose a worksheet column contains identifiers and the macro should locate the first exact match. A comparison such as If cell.Value = target Then expresses an exact match. If partial text matches are intended instead, use a suitable text-search approach and account for case sensitivity and empty cells. The stopping statement does not decide what counts as a match; the condition immediately before it does.

Nested loops: Exit For leaves only one loop

A frequent source of confusion is nested loops. If an Exit For appears inside an inner loop, VBA exits only that inner loop. The outer loop continues with its next iteration. VBA does not interpret one Exit For as a request to leave every active For loop.

For example, a two-dimensional search might inspect every cell in a block. To stop the entire search at the first match, use a Boolean flag: exit the inner loop when a match is found, then check the flag in the outer loop and exit that too.

Sub FindValueInBlock()
    Dim rowNumber As Long
    Dim columnNumber As Long
    Dim found As Boolean
    Dim target As Variant

    target = "P-104"
    found = False

    ' Search rows and columns; leave both loops after a match.
    For rowNumber = 1 To 20
        For columnNumber = 1 To 5
            If Worksheets("Sheet1").Cells(rowNumber, columnNumber).Value = target Then
                found = True
                Exit For
            End If
        Next columnNumber

        If found Then Exit For
    Next rowNumber

    If found Then
        MsgBox "Match found at row " & rowNumber & ", column " & columnNumber
    Else
        MsgBox "No match found."
    End If
End Sub

After an early exit from a numeric For loop, its counter retains the value at which the loop was interrupted; it is not automatically advanced to the next value. That is why this example can use rowNumber and columnNumber to identify the matching position after the loops. In more complicated code, storing the matching row and column in separate variables can make the result easier to understand and maintain.

For Each loops and worksheets

For Each is often convenient when the items are objects, such as worksheets, cells, or workbooks, rather than numbers. It accepts the same early-exit statement. For example, a macro can inspect worksheets until it finds one with a particular name, then stop checking the remaining sheets.

When searching cells, make sure the range is the one intended. A loop over Range("A:A") may inspect a very large number of cells, even if only a small part of the column is populated. A defined range, an Excel table’s data body, or a carefully determined last-used row may be more appropriate. Exiting as soon as a match is found can save work, but it does not make an unnecessarily broad search range a good design by itself.

Also consider what should happen if the search item is not present. A useful macro handles both outcomes: it reports success when it finds a match and gives a clear result when it reaches the end of the range. Avoid relying on the last cell examined as an indirect way to infer whether a match occurred.

Common mistakes and how to avoid them

  • Putting Exit For outside a loop: It must appear within a For...Next or For Each...Next block. VBA will report a compile error if it is not inside a For loop.
  • Removing Next: Keep the matching Next statement in the procedure. It marks the loop structure in the source code, even when a particular run exits before reaching it normally.
  • Expecting all nested loops to stop: One statement exits only the innermost active For loop. Use a flag and a second exit check, or another clearly structured design, to leave outer loops too.
  • Using Exit For when the loop should finish normally: If every item must be processed, do not exit on the first qualifying item. Instead, collect all matches or apply the required action to each one.
  • Leaving a result undefined: Initialize flags and result variables before entering the loop. Then handle the no-match case after it ends.
  • Confusing an early exit with an error: Exit For is normal control flow. It does not raise an error or automatically show a message.

Indentation helps reveal which loop an exit belongs to. In nested code, align each For, Next, and its related Exit For consistently. A short comment can also explain why the loop stops, particularly when the condition is not obvious from its name.

Exit For compared with other VBA control statements

Use the control statement that matches the loop type. Exit For leaves a For loop. For a Do...Loop, VBA provides Exit Do. A conditional loop can also be designed to stop when its condition becomes false, but an explicit exit is useful when a separate event, such as finding a match, should end it immediately.

Exit Sub and Exit Function leave the entire procedure, not just the current loop. They can be appropriate when no more work in the procedure is needed, but they skip any statements that would otherwise run after the loop. Use them carefully if later code must display a result, restore application settings, or perform other cleanup.

In some cases, changing the loop bounds or using a conditional loop can be clearer than adding an early exit. For example, if the number of items to process is known before the loop begins, set the correct upper limit. If the stopping point depends on a value discovered during processing, Exit For is often the clearest direct expression.

Running and debugging the macro safely

On Windows, open the Visual Basic Editor with Alt+F11, or use Developer > Visual Basic. On Mac, use Developer > Visual Basic; the keyboard shortcut may depend on the keyboard and macOS function-key settings. Excel for the web can open a workbook containing VBA, but it cannot create, edit, or run VBA macros; use the desktop Excel application.

Before running code that changes worksheet contents, save a separate copy of the workbook. Ctrl+Z does not undo VBA macro actions. Save a macro-enabled workbook as an Excel Macro-Enabled Workbook (.xlsm) if you need to retain its VBA project. Only enable macros in files you trust.

To inspect an early exit, place the insertion point on a line inside the loop and press F9 to set a breakpoint in the Visual Basic Editor. Run the macro, then step through it with F8. When execution reaches Exit For, observe that the next executed line is after the corresponding loop. On Mac, the function-key behavior can vary with system settings, so use the editor’s Debug menu if F8 is intercepted by macOS or the keyboard.

Frequently Asked Questions

Does Exit For stop the whole macro?
No. It leaves only the current For loop. VBA continues with the first statement after that loop unless the code separately exits the procedure or encounters another control statement.

Do I still need Next after Exit For?
Yes. Keep the matching Next statement in the code to close the loop structure. During a run that reaches Exit For, execution jumps past that loop to the statement after its Next.

Can I use Exit For inside For Each?
Yes. Exit For can stop a For Each...Next loop, including one iterating through worksheet cells or worksheets. It exits at the first point VBA executes the statement.

How do I exit two nested For loops?
Use a flag or saved result: exit the inner loop when the condition is met, then test the flag after the inner loop and exit the outer loop too. A single Exit For does not leave both loops.

What is the difference between Exit For and Exit Do?
Exit For leaves a For loop, while Exit Do leaves a Do loop. Choose the statement that matches the loop structure in your procedure.

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.