更新時間:2022-09-09 09:56:18 來源:動力節(jié)點 瀏覽6286次
當我們要根據(jù)特定條件退出For循環(huán)時,使用Exit For語句。當執(zhí)行Exit For時,控件會立即跳轉(zhuǎn)到For循環(huán)之后的下一條語句。
以下是VBA中Exit For語句的語法。
Exit For
以下示例使用Exit For。如果 Counter 的值達到 4,則退出 For 循環(huán),控制跳轉(zhuǎn)到 For 循環(huán)之后的下一條語句。
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
執(zhí)行上述代碼時,它會在消息框中打印以下輸出。
The value is i is : 0
The value is i is : 2
The value is i is : 4
The value is i is : 40