Excel Guides

Exiting a For Next Loop Early in Excel

There are a few different ways to exit a For Next loop early in Excel. One way is to use the Exit For statement. This statement will immediately exit the loop and continue execution at the next statement after the loop. Another way to exit a loop early is to use a GoTo statement within the loop. This will jump execution to the specified line label, which must be outside of the loop. Finally, you can also use a While Wend loop instead of a For Next loop. This type of loop will continue executing until the condition is no longer true. You can use an Exit While statement within this type of loop to exit early.

Here is an example of using the Exit For statement to exit a For Next loop early:

For i = 1 To 100
    If i = 50 Then
        Exit For
    End If

    'Your code here
Next i

In this example, the code inside the loop will execute 50 times. On the 51st iteration, the code will hit the Exit For statement and immediately exit the loop. Execution will then continue at the next statement after the loop.

Here is an example of using a GoTo statement within a For Next loop:

For i = 1 To 100

    'Your code here

    If i = 50 Then
        GoTo ExitLoop
    End If
Next i
ExitLoop:  'This label must be outside of the loop

In this example, execution will start at the beginning of the For Next loop and iterate through each value from 1-100. The code inside the loop will execute on each iteration. If i equals 50, then execution will jump to the line label "ExitLoop". This label must be outside of (after) the For Next loop. Once execution hits this line label, it will continue on to any code after it.

Move beyond 

Excel

Get started with Causal today.
Build models effortlessly, connect them directly to your data, and share them with interactive dashboards and beautiful visuals.