VBA - 退出 For



在明确某项准则条件下,我们想退出 For 循环时,会用到 Exit For 语句。执行 Exit For 时,控制权会立即跳至 For 循环后的下一个语句。

语法

以下为 VBA 中 Exit For 语句的语法。

 Exit For

流程图

VBA Exit For statement

示例

以下示例使用了 Exit For。如果计数器的值达到 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 
vba_loops.htm
广告