VB 循环

For Next、For Each、Do Loop、While,以及退出与嵌套。

Beginner
Key Points次数已知用 For,遍历集合用 For Each,条件驱动用 Do Loop;VBScript 没有 break/continue。

For Next

VBSCRIPT
Dim i, sum
sum = 0
For i = 1 To 10
    sum = sum + i
Next
WScript.Echo "1..10 的和 = " & sum

For i = 10 To 1 Step -2
    WScript.Write i & " "
Next
WScript.Echo ""
Output
1..10 的和 = 55
10 8 6 4 2

Step may be negative (counting down) or fractional; it defaults to 1. For i = 1 To 10 runs ten times, inclusive at both ends — unlike C-style i < 10, so off-by-one mistakes are easy.

For Each

VBSCRIPT
Dim langs, lang
langs = Array("VBScript", "JScript", "PowerShell")

For Each lang In langs
    WScript.Echo lang
Next

' 遍历字典的值
Dim d
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Apple"
d.Add "b", "Banana"

Dim k
For Each k In d.Keys
    WScript.Echo k & " = " & d(k)
Next
Output
VBScript
JScript
PowerShell
a = Apple
b = Banana

For Each only iterates and gives no index; use For i = 0 To UBound(arr) when you need one. Never add or remove items while enumerating — it upsets the enumerator.

Do Loop

VBSCRIPT
' 先判断后执行
Dim n
n = 0
Do While n < 3
    WScript.Echo "n = " & n
    n = n + 1
Loop

' 先执行后判断
Dim m
m = 0
Do
    WScript.Echo "m = " & m
    m = m + 1
Loop Until m >= 3
Output
n = 0
n = 1
n = 2
m = 0
m = 1
m = 2

Do While ... Loop tests first and may run zero times; Do ... Loop Until runs at least once. Use the latter for "must try once" cases such as reading a file or prompting.

While

VBSCRIPT
Dim i
i = 1
While i <= 3
    WScript.Echo i
    i = i + 1
Wend
Output
1
2
3

While ... Wend is the legacy form: test-first only, and no Exit. New code uses Do While ... Loop, which is equivalent but supports Exit Do.

退出循环

VBSCRIPT
Dim i
For i = 1 To 100
    If i * i > 50 Then
        WScript.Echo "第一个平方超过 50 的数是 " & i
        Exit For
    End If
Next

Dim j
j = 0
Do
    j = j + 1
    If j = 5 Then Exit Do
Loop
WScript.Echo "j = " & j
Output
第一个平方超过 50 的数是 8
j = 5

Exit For and Exit Do leave only the innermost loop. To break out of nested loops, set a flag and check it in the outer loop — VBScript has no labelled break.

跳过本次

VBSCRIPT
Dim i
For i = 1 To 10
    If i Mod 2 = 0 Then
        ' 没有 Continue For,只能把逻辑放进 If 里
    Else
        WScript.Echo i
    End If
Next
Output
1
3
5
7
9

VBScript has no Continue. Either wrap the body in an If or hand-control a Do ... Loop — the latter reads worse, so the If is usual.

嵌套与性能

VBSCRIPT
Dim i, j, count
count = 0
For i = 1 To 100
    For j = 1 To 100
        count = count + 1
    Next
Next
WScript.Echo "内层执行了 " & count & " 次"
Output
内层执行了 10000 次
VBScript is interpreted, so every statement in a loop pays parsing cost; loops over a hundred thousand iterations feel slow. Hoist invariant work (UBound, Len, object property access) out of the loop for a large speedup.

Friends & Partners