Exit Statement

Exits a block of Do...Loop, For...Next, Function, or Sub code.

Syntax

Exit Do

Exit For

Exit Function

Exit Sub

Remarks

The Exit statement syntax has these forms:

Exit Do

Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where it occurs.

Exit For

Provides a way to exit a For loop. It can be used only in a For...Next or For Each...Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where it occurs.

Exit Function

Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function.

Exit Sub

Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub.

The following example illustrates the use of the Exit statement

Example 1:


Sub RandomLoop
   Dim I, MyNum
   
      For I = 1 To 1000   ' Loop 1000 times.
         MyNum = Int(Rnd * 100)   ' Generate random numbers.
         Select Case MyNum   ' Evaluate random number.
            Case 17 'Operations based on the requirement for this case
               Exit For   ' If 17, exit For...Next.            
            Case 54 'Operations based on the requirement for this case
               Exit Sub   ' If 54, exit Sub procedure.
            End Select
      Next
End Sub

Example 2:


Function CalculateValue(x)
        If x < 0 Then
             CalculateValue = 0
             Exit Function
        End If
        CalculateValue = x * 4
End Function
'In this example, if x is negative, the function returns 0 and exits before executing any further calculations.

Example 3:


Dim count 
count = 0 
Do While True 
        count = count + 1 
        If count > 10 Then 
                Exit Do ' Exits the loop after count exceeds ten.
        End If 
        ' Additional processing...
Loop 
'Here, once count exceeds 10, the loop will terminate.

Example 4:


For i = 1 To 10
        If i = 5 Then
                Exit For ' Exits the loop when i equals 5.
        End If
        ' Code for other iterations...
Next
'In this case, when i reaches 5, the loop terminates early.