How To Exit A VBA Loop

Hi, there are times when you need to exit a loop after a certain condition has been met.

How do you exit function in VBA?

In the following example, you are going to see how to exit a function in VBA:

Sub StartNumbers()
    Dim intNumber As Integer
    
    intNumber = ExitTest
    
    'the number is going to be 3
    MsgBox "The number is " & intNumber
    
End Sub

Function ExitTest() As Integer
    Dim intCounter As Integer
    
    For intCounter = 1 To 5
        If intCounter = 3 Then
            ExitTest = intCounter
            Exit Function
        End If
    Next
End Function

How do you stop loop in VBA?

In the following example you’ll discover how easy it is to exit the vba loop.

For the “For” loop just tell the code, to “Exit For”.

and for the “Do” Loop just tell the code to “Exit Do”.

Sub ExitForLoop()
    
    Dim intCount As Integer
    
    For intCount = 1 To 100
        
        Debug.Print intCount
        
        If intCount = 50 Then
            MsgBox "50 has been reached.  Now exiting...", , "Exit For"
            Exit For
        End If
    Next
    
End Sub

Sub ExitDoLoop()
    
    Dim intCount As Integer
    
    Do Until intCount = 100
        
        Debug.Print intCount
        
        If intCount = 50 Then
            MsgBox "50 has been reached.  Now exiting...", , "Exit Do"
            Exit Do
        End If
        
        intCount = intCount + 1
    Loop
    
End Sub

In some instances “Exit For” or “Exit Do” doesn’t work. In these cases try using the keyword “End” (check out this sample) or add a “Go To (something)” label, then exit the sub there.

Want to see a “Do WHILE LOOP” in Access VBA? Ciick me.

You are also going to find out:
What does a loop do in VBA?

Hopefully that helps someone. Let me know if you have any questions.

Click here for related posts on looping and exiting in VBA.



Comments are closed.