Do…Loop Statement

Repeats a block of statements while a condition is True or until a condition becomes True.

Syntax


Do {While | Until} condition
   [statements]
   [Exit Do]
   [statements]
Loop               

'or use below syntax

Do
  [statements] 
  [Exit Do]
  [statements]
Loop {While | Until} condition

Arguments:

  • Condition: Numeric or string expression that is True or False. If condition is Null, condition is treated as False.

  • Statements: One or more statements that are repeated while or until condition is True.

Remarks

The Exit Do can only be used within a Do...Loop control structure to provide an alternate way to exit a Do...Loop. Any number of Exit Do statements may be placed anywhere in the Do...Loop. Often used with the evaluation of some condition (for example, If...Then), Exit Do transfers control to the statement immediately following the Loop.

When used within nested Do...Loop statements, Exit Do transfers control to the loop that is nested one level above the loop where it occurs.

The following examples illustrate use of the Do...Loop statement:

Example 1:


Dim flag , MyNum
flag = true  'initialises a variable
Do Until  flag= false
   MyNum = Int (6 * Rnd + 1)   ' Generate a random integer between 1 and 6.
   If MyNum = 4 Then
       flag=false 
  End If
Loop 

Example 2:


Dim Check, Counter
Check = True   'Initialize variables.
Counter = 0   ' Initialize variables.
Do                            ' Outer loop.
   Do While Counter < 20      ' Inner loop.
      Counter = Counter + 1   ' Increment Counter.
      If Counter = 10 Then    ' If condition is True...
         Check = False        ' set value of flag to False.
         Exit Do              ' Exit inner loop.
      End If
   Loop
Loop Until Check = False      ' Exit outer loop immediately.

Example 3:


Dim index
index = 0
Dim items(5)
items(0) = "Item1"
items(1) = "Item2"

Do While index < UBound(items)
	index = index + 1
Loop

Example 4:


Dim count
count = 0
Do 
    'Operations based on requirement 
    count = count + 1
Loop While count < 1 ' Will exit after one iteration.

Example 5:


Dim Val
Val =2
Do 
    If Val=5 Then Exit Do
    Val= Val+1
    'Operations based on requirement using value of Val
Loop While Val<10

Example 6:

Dim Row, Col
Row= 1
Col =1
Do
    Col =1 
    Do 
        'Operations based on requirement using Row and Col
        Col = Col +1
    Loop While Col<4
    Row = Row +1
Loop While Row<4