VBA - Exit Do



An Exit Do Statement is used when we want to exit the Do Loops based on certain criteria. It can be used within both Do…While and Do...Until Loops.

When Exit Do is executed, the control jumps to the next statement immediately after the Do Loop.

Syntax

Following is the syntax for Exit Do Statement in VBA.

 Exit Do

Example

The following example uses Exit Do. If the value of the Counter reaches 10, the Do Loop is exited and the control jumps to the next statement immediately after the For Loop.

Private Sub Constant_demo_Click()
   i = 0
   Do While i <= 100
      If i > 10 Then
         Exit Do   ' Loop Exits if i>10
      End If
      MsgBox ("The Value of i is : " & i)
      i = i + 2
   Loop
End Sub

When the above code is executed, it prints the following output in a message box.

The Value of i is : 0

The Value of i is : 2

The Value of i is : 4

The Value of i is : 6

The Value of i is : 8

The Value of i is : 10
vba_loops.htm
Advertisements