Exit 陳述式

結束 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 之陳述式後的陳述式。

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.