Exit文

Do...LoopFor...NextFunctionまたはSubコードのブロックを終了します。

構文

Exit Do

Exit For

Exit Function

Exit Sub

備考

Exit文の構文には次の形式があります:

Exit Do

Do...Loop文を終了する方法を提供します。Do...Loop文内でのみ使用できます。Exit Doは、Loop文に後続する文に制御を移します。ネストされたDo...Loop文内で使用すると、Exit Doは、それが発生したループのネストされた1レベル上のループに制御を移します。

Exit For

Forループを終了する方法を提供します。For...NextループまたはFor Each...Nextループでのみ使用できます。Exit Forは、Next文に後続する文に制御を移します。ネストされたForループ内で使用すると、Exit Forは、それが発生したループのネストされた1レベル上のループに制御を移します。

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.