top of page

How to exit a For or a While loop in VBA?

How to exit a loop.

vba exit loop

I am choosing to have this exit loop section separately from the loops in the vba basics section as I feel like the 'Exit do' or 'Exit For' syntaxes are often forgotten. I have seen a lot of VBA code with a lot of unnecessary Error handling parts that could have been eliminated. In general I feel like most codes can be written without error handling syntaxes by encapsulating them in if statements or some things in variables instead avoiding any error handling which in my perspective leaves you with a cleaner code and less "jumping" around.


My Worksheet below

exit while or for loop

How to Exit a Do Loop


Sub ExitDO()

Dim i As Integer
 
Do While i < 10
        i = i + 1
 
        If Cells(i, 1) = "Thx." Then
 Exit Do
        End If
Loop

'Displays Thx. in the message box as shown below. 
MsgBox "My final destination is '" & Cells(i, 1) & "'"

End Sub

How to Exit a For Loop


Sub ExitFOR()
For i = 1 To 10
    If Cells(i, 1) = "Thx." Then
 Exit For
    End If
Next i
 
'Displays Thx. in the message box as shown below. 
MsgBox "My final destination is '" & Cells(i, 1) & "'"

End Sub


116 views0 comments

Comments


bottom of page