条件が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になるまで繰り返される1つ以上の文。
備考
Exit Doは、Do...Loop制御構造内でのみ使用でき、Do...Loopを終了する別の方法を提供します。Do...Loop内の任意の場所に任意の数のExit Do文を配置できます。Exit Doは多くの場合、なんらかの条件(If...Thenなど)の評価で使用され、ループの直後の文に制御を移します。
ネストされたDo...Loop文内で使用すると、Exit Doは、それが発生したループのネストされた1レベル上のループに制御を移します。
次の例は、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