Do - While

This should be used in situations when you want to loop while a condition is true.
You can test the condition at the top or at the bottom of the loop.


Condition At The Top

This might not be executed because the condition is at the top.
This loops while the variable has a value less than 5 (four times).

Public Sub DoWhile1() 
Dim icount As Integer
icount = 1
Do While (icount < 5)
'do something
icount = icount + 1
Loop
End Sub

Condition At The Bottom

This is executed at least once because the condition is at the bottom.
This loops while the variable has a value less than 5 (four times).

Public Sub DoWhile2() 
Dim icount As Integer
   icount = 1
   Do
'do something
      icount = icount + 1
   Loop While (icount < 5)
End Sub

Nested Do - While

You can nest loops inside one another.
In this example you need to reset the inner variable inside the outside loop.

Public Sub DoWhile3() 
Dim iouter As Integer
Dim inner As Integer
   iouter = 1
Do While (iouter < 5)
      inner = 1 'reset variable
      Do While (inner < 5)
'do something
         inner = inner + 1
      Loop
iouter = iouter + 1
Loop
End Sub

Exit Do

The Exit Do statement lets you exit the loop early.


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext