VB 程序

Sub 与 Function、参数传递、ByVal / ByRef、递归与可选参数。

Beginner
Key PointsSub 只做事不返回值,Function 用「给函数名赋值」返回结果;参数默认 ByRef。

Sub

VBSCRIPT
Sub Greet(name)
    WScript.Echo "Hello, " & name
End Sub

Call Greet("Ada")
Greet "Bob"              ' 不用 Call 时不能加括号
Output
Hello, Ada
Hello, Bob

Call Greet("Ada") and Greet "Bob" both work, but Greet("Bob") does not: without Call, parentheses are parsed as passing a single expression and multi-argument calls fail.

Function

VBSCRIPT
Function Add(a, b)
    Add = a + b
End Function

Function IsEven(n)
    If n Mod 2 = 0 Then
        IsEven = True
    Else
        IsEven = False
    End If
End Function

WScript.Echo Add(3, 4)
WScript.Echo IsEven(10)
WScript.Echo IsEven(7)
Output
7
True
False

Return by assigning to the function name; there is no return. A missing assignment yields Empty with no error, so assign on every branch, especially both paths of an If.

ByVal 与 ByRef

VBSCRIPT
Sub ChangeRef(x)
    x = x + 1
End Sub

Sub ChangeVal(ByVal x)
    x = x + 1
End Sub

Dim a, b
a = 10 : b = 10
ChangeRef a
ChangeVal b
WScript.Echo a & " / " & b
Output
11 / 10

Parameters are ByRef by default, so changes propagate to the caller — unlike Java, C# and Python. Write ByVal explicitly unless you intend to write back.

可选参数

VBSCRIPT
Function Greeting(name, Optional title = "先生")
    Greeting = "你好," & name & title
End Function

WScript.Echo Greeting("张伟")
WScript.Echo Greeting("李娜", "女士")
Output
你好,张伟先生
你好,李娜女士

Optional parameters must come last and need a default. Skipping a middle one uses an empty slot: F(a, , c) — poor readability, so prefer a dictionary for many parameters.

递归

VBSCRIPT
Function Fact(n)
    If n <= 1 Then
        Fact = 1
    Else
        Fact = n * Fact(n - 1)
    End If
End Function

Function Fib(n)
    If n < 2 Then
        Fib = n
    Else
        Fib = Fib(n - 1) + Fib(n - 2)
    End If
End Function

WScript.Echo Fact(5)
WScript.Echo Fib(10)
Output
120
55

Naive Fib is exponential: Fib(35) takes seconds. VBScript has no tail-call optimisation and deep recursion overflows the stack — prefer loops in production scripts.

作用域与 Exit

VBSCRIPT
Sub Demo()
    Dim i
    For i = 1 To 10
        If i = 3 Then Exit Sub        ' 提前退出过程
    Next
End Sub

Function Find(arr, target)
    Dim i
    Find = -1
    For i = LBound(arr) To UBound(arr)
        If arr(i) = target Then
            Find = i
            Exit Function             ' 提前返回
        End If
    Next
End Function

Exit Sub / Exit Function are the only early exits — there is no break or continue. To skip an iteration, wrap the body in an If.

Friends & Partners