VBA - Exit For 语句
当我们想要根据某些条件退出For循环时,使用Exit For语句。 当执行Exit For时,控制立即跳转到For循环之后的下一条语句。
语法
以下是 VBA 中 Exit For 语句的语法。
Exit For
流程图

示例
以下示例使用Exit For。 如果 Counter 的值达到 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