退出 Do...Loop、For...Next、Function 或 Sub 代码块。
语法
Exit Do
Exit For
Exit Function
Exit Sub
注释
Exit 语句语法有以下形式:
Exit Do
提供了退出 Do...Loop 语句的方法。它只能在 Do...Loop 语句内使用。Exit Do 会将控制权转移到 Loop 语句后面的语句。在嵌套的 Do...Loop 语句中使用时,Exit Do 会将控制权转移到当前循环的上一层嵌套循环。
Exit For
提供了退出 For 循环的方法。它只能在 For...Next 或 For Each...Next 循环中使用。Exit For 会将控制权转移到 Next 语句后面的语句。在嵌套的 For 循环中使用时,Exit For 会将控制权转移到当前循环的上一层嵌套循环。
Exit Function
立即退出当前所在的 Function 过程。将继续执行调用 Function 的语句后面的语句。
Exit Sub
立即退出当前所在的 Sub 过程。将继续执行调用 Sub 的语句后面的语句。
以下示例说明了 Exit 语句的用法
示例 1:
Sub RandomLoop
Dim I, MyNum
For I = 1 To 1000 ' Loop 1000 times.
MyNum = Int(Rnd * 100) ' Generate random numbers.
Select Case MyNum ' Evaluate random number.
Case 17 'Operations based on the requirement for this case
Exit For ' If 17, exit For...Next.
Case 54 'Operations based on the requirement for this case
Exit Sub ' If 54, exit Sub procedure.
End Select
Next
End Sub
示例 2:
Function CalculateValue(x)
If x < 0 Then
CalculateValue = 0
Exit Function
End If
CalculateValue = x * 4
End Function
'In this example, if x is negative, the function returns 0 and exits before executing any further calculations.
示例 3:
Dim count
count = 0
Do While True
count = count + 1
If count > 10 Then
Exit Do ' Exits the loop after count exceeds ten.
End If
' Additional processing...
Loop
'Here, once count exceeds 10, the loop will terminate.
示例 4:
For i = 1 To 10
If i = 5 Then
Exit For ' Exits the loop when i equals 5.
End If
' Code for other iterations...
Next
'In this case, when i reaches 5, the loop terminates early.