To end a VBA loop early, use Exit For inside a For loop or Exit Do inside a Do loop. Use Next or Loop to reach a loop’s normal end; the VBA statement End is not a substitute for either one.
What “end loop” means in VBA
People searching for “Excel VBA end loop” may mean several different things: how to finish a loop normally, how to leave it as soon as a condition is met, or how to stop a macro that is currently stuck. VBA handles these situations in different ways, so choosing the right statement matters.
A loop repeats a block of instructions. In a For loop, VBA reaches Next and either advances the counter or finishes when the loop limit has been reached. A Do loop reaches Loop and checks its condition according to whether the condition appears at the start or end. If you need to leave before that normal point, use the matching Exit statement.
Before running any macro that changes a workbook, save a separate copy. Excel’s Undo command, Ctrl+Z on Windows or Command+Z on Mac, does not undo VBA macro actions. Keep working code in a macro-enabled workbook, usually an .xlsm file.
End a For loop with Exit For
Use Exit For when the loop has found what it needs or when continuing would serve no purpose. VBA immediately leaves the nearest active For or For Each loop and continues with the first statement after that loop. It does not automatically end the containing procedure.
For example, this macro searches column A on a worksheet named Data for a particular code and stops at the first match. Open the Visual Basic Editor with Alt+F11 on Windows. On Mac, use Option+F11 (some keyboards also require Fn), or open the editor from Excel’s Tools menu.
Sub FindFirstCode()
Dim ws As Worksheet
Dim cell As Range
Dim target As String
Set ws = ThisWorkbook.Worksheets("Data")
target = "Q7"
For Each cell In ws.Range("A2:A100")
If CStr(cell.Value2) = target Then
MsgBox "Found in row " & cell.Row
Exit For ' Leave this For Each loop after the first match.
End If
Next cell
End Sub
If the value appears more than once, the example reports only the first match because Exit For stops the search. Remove that statement if the macro should process every matching cell. The range is deliberately limited to A2:A100; change it to suit the data, or calculate a last row if the list size varies.
End a Do loop with Exit Do
Use Exit Do to leave a Do loop early. This works with loops that test a condition at the beginning, loops that test at the end, and loops that repeat until explicitly exited. The following example scans down column A until it reaches an empty cell.
Sub ProcessUntilBlank()
Dim ws As Worksheet
Dim rowNum As Long
Set ws = ThisWorkbook.Worksheets("Data")
rowNum = 2
Do While rowNum <= ws.Rows.Count
If Len(CStr(ws.Cells(rowNum, "A").Value2)) = 0 Then
Exit Do ' Stop at the first blank in column A.
End If
Debug.Print ws.Cells(rowNum, "A").Value2
rowNum = rowNum + 1
Loop
End Sub
Here, Exit Do is a safety exit if the blank-cell test is reached. The loop also has a row limit, so it cannot try to address a row beyond the worksheet. The procedure assumes that the first blank in column A marks the end of the list. If blanks can occur within valid data, use a different stopping rule, such as a known last row or a separate completion flag.
A Do While loop checks its condition before each pass, so its body may run zero times. A Do loop with Loop While condition checks after the body, so it runs at least once. That difference is useful when deciding whether to put a condition at the top or bottom; it does not change which statement exits early.
Understand nested loops
When loops are nested, Exit For or Exit Do leaves only the innermost loop of the matching type that contains the statement. It does not jump out of every loop or exit the procedure. For example, if a For loop is inside another For loop, Exit For ends the inner loop. Execution then resumes in the outer loop after the inner loop’s Next.
This behavior is often exactly what a search needs: stop checking columns in the current row, then continue with the next row. If the intended action is to stop both loops, use a clear flag that the outer loop checks, or move the search into a separate function and return a result. A flag is usually easier to read than a jump to a distant label.
- Use
Exit Forto leave the nearest activeFororFor Eachloop. - Use
Exit Doto leave the nearest activeDoloop. - Use
Exit SuborExit Functiononly when you intend to leave the entire procedure.
Skip an iteration instead of ending the loop
VBA does not provide a built-in Continue For or Continue Do statement. If you want to skip the remaining work for one item but keep processing later items, put the work inside an If block that describes the items you do want to process. For instance, a loop can process a cell only when it is not blank, then naturally reach Next for every row.
This is different from Exit For: exiting stops the entire loop, while a conditional block skips work for the current iteration and allows the next iteration to run. A GoTo label can imitate a continue statement in some code, but it can make the path through a procedure harder to follow. Prefer a clear condition unless the loop’s logic genuinely requires a jump.
End, Loop, Next, and Exit are different
Several VBA keywords sound like they might end a loop, but their roles differ:
Nextcloses aFororFor Eachloop and advances or finishes its iteration.Loopcloses aDoloop and returns control to its condition or repeats it.Exit ForandExit Doleave a loop before its normal end.End Subcloses a procedure in the source code; it is not a command to break out of a loop.End, by itself, abruptly terminates VBA execution. It is not a structured loop exit and can reset module-level variables, so it is generally the wrong way to stop a loop.
If your goal is to finish the macro after the loop, place the remaining instructions after the loop, or use an appropriate procedure exit such as Exit Sub. Do not use the standalone End statement just because it appears to stop execution immediately.
Prevent loops that never finish
A loop can run indefinitely when its exit condition never becomes true. A common mistake is forgetting to update a counter: a Do While rowNum <= 10 loop will not finish if rowNum is never increased or otherwise changed. Another is testing the wrong cell or comparing text with a value that can never match.
Before running a loop over worksheet data, check these details:
- Does every path through a counter-based loop update the counter?
- Can the condition become false with the actual data and values?
- Could an error or an early branch skip the instruction that updates the loop state?
- Is there a sensible limit, such as the last used row, rather than an open-ended range?
- Does the code handle blanks, errors, and unexpected cell contents as intended?
For a For loop, make sure the start, end, and step values describe the intended number of passes. A negative step is valid when counting down, but the start and end values must align with it. For a Do loop, inspect the condition and the statement that changes the values it depends on. Testing on a small copy of the workbook can expose logic errors before a macro processes a large sheet.
Stop a macro that is already running
If Excel appears busy because a loop is running, you may be able to interrupt execution rather than edit the code first. In Windows Excel, try Ctrl+Break; keyboard layouts without a dedicated Break key may require a key combination supported by that keyboard. In the Visual Basic Editor, use the Run menu’s Break command when it is available. On Mac, the editor and available interruption keys can vary by keyboard and Excel setup, so use the Visual Basic Editor’s Run menu if a keyboard shortcut is not apparent.
After breaking, inspect the highlighted line and the loop’s condition or counter. Correct the cause before running again. If the macro is changing cells, some changes may already have occurred before the interruption; stopping it does not roll those changes back. This is another reason to save a separate workbook copy before running code that edits data.
Choose the right way to stop
For a predictable number of repetitions, such as processing rows 2 through 100, a For loop is usually straightforward. For a process that continues until a condition occurs, such as reading until a blank row or waiting for a status to change, a Do loop often expresses the rule more naturally. Either type can have an early exit, but use the matching statement and keep the condition easy to understand.
Choose Exit For when a search has found its first result, or when later iterations cannot affect the answer. Choose Exit Do when a condition inside a Do loop signals completion. Use a normal loop condition when the stop rule can be stated clearly at the top or bottom. Use a procedure exit only when the whole macro or function should end. The clearest code makes it obvious both why the loop stops and what the macro does next.
Frequently Asked Questions
How do I end a For Each loop in VBA?
Put Exit For inside the For Each block. It leaves that loop immediately and continues with the statement after its Next. Without it, the loop normally visits each item in its collection or range.
Can I use Exit For inside a Do loop?
No. Exit For exits a For loop, while Exit Do exits a Do loop. Use the statement that matches the loop you want to leave.
Does Exit For stop the whole macro?
No. It exits only the nearest active For or For Each loop. The macro continues with the next statement after that loop. Use Exit Sub to leave a Sub procedure, or Exit Function to leave a Function procedure.
Is there a Continue For command in Excel VBA?
No, VBA does not have a built-in Continue For statement. To skip processing for one item, place the processing code inside an If block whose condition identifies the items to handle; the loop then proceeds to its next iteration normally.
Why does my VBA loop keep running?
Usually, its stop condition is not being reached or the value controlling that condition is not changing. Check the counter update, the condition’s true and false cases, and any branches that bypass the update. You can interrupt a running macro, fix the cause, and rerun it on a saved copy.
Related
- Excel Text to Columns: How to Split Data Into Fields
- Excel Text to Columns: Split Cell Text at Line Breaks
- Excel Text to Columns: Find It and Split Data Correctly
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- VBA Dictionary Split: Turn Text into Keys and ValuesIn VBA, use the Split function to break a string into an array, then add the pieces to…
- VBA Copy Dictionary: Methods, Code, and Deep CopiesTo copy a VBA Scripting.Dictionary, create a second dictionary and add each key and item from the first;…
- VBA Open Excel File and Save as CSV with Working CodeYes. In VBA, open the workbook with Workbooks.Open, then call SaveAs with FileFormat:=xlCSVUTF8 to create a UTF-8 CSV…
- Excel VBA: Find the First Row Above a Value ThresholdTo find the first row where a cell’s value is greater than a threshold, loop through the relevant…
- Excel VBA Bubble Sort for Arrays: Code and ExplanationTo bubble-sort a one-dimensional VBA array, compare neighboring items and swap them when they are out of order;…
- Excel SEQUENCE Macro: Generate Number Series in VBAIf you want a sequence of numbers in Excel, the simplest option is usually the SEQUENCE worksheet function,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.