Do...Loop, For...Next, Function 또는 Sub 코드 블록을 종료합니다.
구문
Exit Do
Exit For
Exit Function
Exit Sub
주석
Exit 명령문 구문의 형식은 다음과 같습니다.
Exit Do
Do...Loop 명령문을 종료하는 방법을 제공합니다. Do...Loop 명령문 내에서만 사용할 수 있습니다. Exit Do는 Loop 명령문 다음에 오는 명령문으로 제어를 전달합니다. 중첩된 Do...Loop 명령문 내에서 사용하는 경우 Exit Do는 루프가 발생하는 루프보다 한 수준 위의 중첩된 루프로 제어를 전달합니다.
Exit For
For 루프를 종료하는 방법을 제공합니다. For...Next 또는 For Each...Next 루프에서만 사용할 수 있습니다. Exit For는 Next 명령문 다음에 오는 명령문으로 제어를 전달합니다. 중첩된 For 루프 내에서 사용하는 경우 Exit For는 루프가 발생하는 루프보다 한 수준 위의 중첩된 루프로 제어를 전달합니다.
Exit Function
표시되는 Function 프로시저를 즉시 종료합니다. 실행은 Function을 호출한 명령문 다음에 오는 명령문을 진행합니다.
Exit Sub
표시되는 Sub 프로시저를 즉시 종료합니다. 실행은 Sub를 호출한 명령문 다음에 오는 명령문을 진행합니다.
다음 예는 Exit 명령문의 사용을 보여줍니다.
예 1:
Sub RandomLoop
Dim I, MyNum
For I = 1 To 1000 ' Loop 1000 times.
MyNum = Int(Rnd * 100) ' Generate random numbers.
Select Case MyNum ' Evaluate random number.
Case 17 'Operations based on the requirement for this case
Exit For ' If 17, exit For...Next.
Case 54 'Operations based on the requirement for this case
Exit Sub ' If 54, exit Sub procedure.
End Select
Next
End Sub
예 2:
Function CalculateValue(x)
If x < 0 Then
CalculateValue = 0
Exit Function
End If
CalculateValue = x * 4
End Function
'In this example, if x is negative, the function returns 0 and exits before executing any further calculations.
예 3:
Dim count
count = 0
Do While True
count = count + 1
If count > 10 Then
Exit Do ' Exits the loop after count exceeds ten.
End If
' Additional processing...
Loop
'Here, once count exceeds 10, the loop will terminate.
예 4:
For i = 1 To 10
If i = 5 Then
Exit For ' Exits the loop when i equals 5.
End If
' Code for other iterations...
Next
'In this case, when i reaches 5, the loop terminates early.