VBA Exit For语句

当想要根据特定标准退出For循环时,就可以使用Exit For语句。当执行Exit For时,控件会立即跳转到For循环之后的下一个语句。

语法

以下是在VBA中Exit For语句的语法。

Exit For

流程图

示例

以下使用Exit For语句的示例。 如果计数器(i)的值达到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
原文地址:https://www.cnblogs.com/sunyllove/p/11348245.html