當想要根據特定標準退出For
迴圈時,就可以使用Exit For
語句。當執行Exit For
時,控制元件會立即跳轉到For
迴圈之後的下一個語句。
以下是在VBA中Exit For
語句的語法。
Exit For
流程圖
以下使用Exit For
語句的範例。 如果計數器(i
)的值達到4
,則退出For
迴圈,並在For
迴圈之後立即跳轉到下一個語句。
Private Sub Constant_demo_Click()
Dim a As Integer
a = 10
For i = 0 To a Step 2 'i is the counter variable and it is incremented by 2
MsgBox ("The value is i is : " & i)
If i = 4 Then
i = i * 10 'This is executed only if i=4
MsgBox ("The value is i is : " & i)
Exit For 'Exited when i=4
End If
Next
End Sub
當執行上面的程式碼時,它將在訊息框中輸出以下輸出。
The value is i is : 0
The value is i is : 2
The value is i is : 4
The value is i is : 40