조건이 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 명령문이 1개 이상 배치될 수 있습니다. 일부 조건(예: If...Then)의 평가와 함께 사용되는 경우 Exit Do는 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