VBA Exit For語句

2019-10-16 23:14:05

當想要根據特定標準退出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