位置:首页 > 高级语言 > VBA在线教程 > VBA退出for循环

VBA退出for循环

Exit For 语句使用在需要依据一定的标准来退出For循环。当Exit For 被执行,控制系统就会马上跳到 For 循环后,下一条语句。

语法:

VBA Exit For 语句的语法:

 Exit For

流程图

VBA Exit For statement

示例 :

下面的示例使用Exit For。如果计数器的值达到4,对于Exit 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