Do…Loop 语句

在条件为 True 时或在条件变为 True 之前重复执行语句块。

语法

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

'or use below syntax

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

参数:

  • Condition:为 True 或 False 的数字或字符串表达式。如果条件为 Null,则将条件视为 False。

  • Statements:在条件为 True 时或在条件变为 True 之前重复执行的一个或多个语句。

注释

Exit Do 只能在 Do...Loop 控制结构中使用,以提供退出 Do...Loop 的替代方式。可以将任意数量的 Exit Do 语句放置在 Do...Loop 中的任何位置。Exit Do 通常与某些条件的求值(例如 If...Then)一起使用,它会将控制权转移到紧跟在 Loop 之后的语句。

在嵌套的 Do...Loop 语句中使用时,Exit Do 会将控制权转移到当前循环的上一层嵌套循环。

以下示例说明了 Do...Loop 语句的用法:

示例 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 

示例 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.

示例 3:

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

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

示例 4:

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

示例 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

示例 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