使用 For...Next 语句
使用 For...下一个 语句将语句块 重复特定次数 。 “For”循环,使用计算器变量(重复循环一次,其值将增加或减少)。
The following procedure makes the computer beep 50 times. The For statement specifies the counter variable and its start and end values. The Next statement increments the counter variable by 1.
Sub Beeps()
For x = 1 To 50
Beep
Next x
End Sub
Using the Stepkeyword, you can increase or decrease the counter variable by the value you specify. 在以下示例中,每次循环重复时,计数器变量 j
都会递增 2。 When the loop is finished, total
is the sum of 2, 4, 6, 8, and 10.
Sub TwosTotal()
For j = 2 To 10 Step 2
total = total + j
Next j
MsgBox "The total is " & total
End Sub
To decrease the counter variable, use a negative Step value. To decrease the counter variable, you must specify an end value that is less than the start value. In the following example, the counter variable myNum
is decreased by 2 each time the loop repeats. When the loop is finished, total
is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.
Sub NewTotal()
For myNum = 16 To 2 Step -2
total = total + myNum
Next myNum
MsgBox "The total is " & total
End Sub
注意
It's not necessary to include the counter variable name after the Next statement. In the preceding examples, the counter variable name was included for readability.
可以退出 For... 使用 Exit For 语句,在计数器达到其结束值之前下一个语句。 例如,发生错误时,可使用 If...Then...Else 语句或 Select Case 语句的 True 语句块中的 Exit For 语句,它专用于检查错误。 如果未发生错误,则 If...然后。。。Else 语句为 False,循环将继续按预期运行。
另请参阅
支持和反馈
有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。