Exit Do
This statement provides a way to exit the loop early.
It can only be used inside a Do - While, Do - Until or a Do - Loop.
This transfers control to the statement that immediately follows the Loop statement.
Exit Do
Do - While
This loops will exit at the start of the third loop.
Public Sub ExitDo1()
Dim icount As Integer
icount = 1
Do While (icount < 5)
If (icount = 3) Then
Exit Do
End If
icount = icount + 1
Loop
End Sub
Do - Until
This loop will exit at the end of the second loop.
Notice that the variable icount is incremented at the start of the loop.
Public Sub ExitDo2()
Dim icount As Integer
icount = 1
Do Until (icount = 5)
icount = icount + 1
If (icount = 3) Then
Exit Do
End If
Loop
End Sub
Do - Loop
This loops through four times.
Public Sub ExitDo3()
Dim icount As Integer
icount = 1
Do
If (icount = 5) Then
Exit Do
End If
icount = icount + 1
Loop
End Sub
Nested Loops
This statement transfers control to the statement that immediately follows the Loop statement.
If a loop is nested, the control is passed only one level up.
Public Sub ExitDo4()
Dim iouter As Integer
Dim inner As Integer
iouter = 1
Do While (iouter < 5)
inner = 1 'reset variable
Do While (inner < 5)
If (inner = 3) Then
Exit Do 'only exits the inner do
End If
inner = inner + 1
Loop
iouter = iouter + 1
Loop
End Sub
Important
You can use one or more Exit Do statements inside the same loop.
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext