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

语法

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

Exit For

流程图

VBA 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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-18
  • 2021-08-21
  • 2022-02-08
猜你喜欢
  • 2022-02-06
  • 2022-12-23
  • 2022-12-23
  • 2021-06-03
  • 2021-08-02
  • 2022-12-23
  • 2021-06-28
相关资源
相似解决方案