VBS_For_next

时间:2023-03-09 00:39:53
VBS_For_next

指定循环次数,使用计数器重复运行语句,语法结构如下:

1
2
3
4
5
For counter = start To end [Step step]
    [statements]
    [Exit For]
    [statements]
Next

主要参数:

       counter:用做循环计数器的数值变量。这个变量不能是数组元素或用户自定义类型的元素。

       start:counter的初值。

       end:counter的终值。

       step:counter的步长。如果没有指定,则step的默认值为1。

   具体示例代码如下:

For…Next

1
2
3
4
5
Dim Count:Count = 0 '定义一个变量,并赋值为0
For i = 1 To 10 '循环10次
    Count = Count + 1
Next
MsgBox Count '输出10

     Step设置计数器循环步长

1
2
3
4
5
Dim Count:Count = 0 '定义一个变量,并赋值为0
For i = 1 To 10 Step 2 '设置计数器步长为2,循环5次
    Count = Count + 1
Next
MsgBox Count '输出5

退出循环

Exit For 语句用于在计数器达到其终止值之前退出 For...Next 语句。因为通常只是在某些特殊情况下(例如在发生错误时)要退出循环,所以可以在 If...Then...Else 语句的 True 语句块中使用 Exit For 语句。如果条件为 False,循环将照常运行。

1
2
3
4
5
6
7
8
Dim Count:Count = 0 '定义一个变量,并赋值为0
For i = 1 To 10 '循环10次
    Count = Count + 1
    If Count = 5 Then '当变量Count的值为5时,退出当前循环
        Exit For
    End If
Next
MsgBox Count '输出5