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