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 的方式。可以在 Do...Loop 中的任何位置放置任何數目的 Exit Do 陳述式。Exit Do 通常與某些條件 (例如 If...Then) 的評估搭配使用,會將控制項傳輸至緊接迴圈之後的陳述式。

在巢狀 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