excel-exit-from-a-for-next-loop-when-a-condition-is-met

Excel - Exit From A For Next Loop When A Condition Is Met

This macro exits a for next loop when a certain condition is met.

Excel

  • 2323
  • 1730
  • 0
  • 0
Add to collection
© 2024VBAmacros.net

1 Open MS Excel.

2 Create a blank workbook.


3 Go to Developer's tab > click on "Visual Basic" button or hit Alt + F11.


4 Go to Insert tab > click on "Module" or hit M.


5 Copy the VBA code from below.

6 Paste the code in the newly created module.


7 Go to Run tab > click on "Run Sub/UserForm" or hit F5.


8 That's it!


Advertisement

Code
'==========================================
' Exit A For Next Loop
'==========================================
Sub exitForNextLoop()
    ' Set variables
    Dim i As Integer
    ' Loop from 1 to 10
    For i = 1 To 10
        ' Check if counter is greater than 8
        If i > 8 Then
            ' Exit for
            Exit For
        End If
        ' Write outpput to the worksheet
        ThisWorkbook.Worksheets(1).Cells(i, 2) = i
    Next i
End Sub
Advertisement


Comments
Sort by:
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
VBAmacros.net VBAmacros.net
Code was successfully copied!
VBAmacros.net VBAmacros.net
Please sign in!
VBAmacros.net VBAmacros.net
You've already voted!