VBA Do ... While loop

A Do...whileloop as long as the condition is true for a group of repeat statements. This condition can be checked at the end of the cycle or at the beginning of the cycle.

grammar

The following is a VBA Do...Whilesyntax cycle.

Do While condition
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop

flow chart

Examples

The following example uses a Do...whileloop to check the conditions at the beginning of the cycle. Inside the loop is executed only when the condition is satisfied.

Private Sub Constant_demo_Click()
   Do While i < 5
      i = i + 1
      msgbox "The value of i is : " & i
   Loop
End Sub

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

The value of i is : 1

The value of i is : 2

The value of i is : 3

The value of i is : 4

The value of i is : 5

Backup / alternative syntax

Another alternative statement is a for...whileloop, for checking the condition at the end of the cycle. The following example illustrates the syntax of these two major differences. grammar-

Do 
   [statement 1]
   [statement 2]
   ...
   [statement n]
   [Exit Do]
   [statement 1]
   [statement 2]
   ...
   [statement n]
Loop While condition

Examples

The following example uses a Do...whileloop to check the conditions at the end of the cycle. Statements inside the loop executes at least once, even if the condition is False.

Private Sub Constant_demo_Click() 
   i = 10
   Do
      i = i + 1
      MsgBox "The value of i is : " & i
   Loop While i < 3 'Condition is false.Hence loop is executed once.
End Sub

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

 

 

Guess you like

Origin www.cnblogs.com/sunyllove/p/11348233.html