VBScript 函数

VBScript 函数详解

VBScript 支持两种可重复使用的代码块:Function(函数)Sub(子程序)
两者区别在于:Function 可以返回值Sub 不能返回值

1. Function(函数)语法

用于计算并返回一个值。

基本语法

Function 函数名(参数1, 参数2, ..., 参数n)
    ' 代码块
    函数名 = 返回值   ' 关键:通过函数名赋值来返回值
End Function

或者使用显式 Return(VBScript 不支持 return 关键字,但可以用函数名赋值)

示例1:简单加法函数

Option Explicit

Function Add(a, b)
    Add = a + b   ' 返回值赋给函数名
End Function

Dim result
result = Add(15, 25)
MsgBox "15 + 25 = " & result   ' 输出 40

示例2:判断奇偶数

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

Dim number
number = CInt(InputBox("请输入一个数字:"))

If IsEven(number) Then
    MsgBox number & " 是偶数"
Else
    MsgBox number & " 是奇数"
End If

示例3:返回字符串(大小写转换)

Function ReverseCase(str)
    Dim i, char, result
    result = ""
    For i = 1 To Len(str)
        char = Mid(str, i, 1)
        If char = LCase(char) Then
            result = result & UCase(char)
        Else
            result = result & LCase(char)
        End If
    Next
    ReverseCase = result
End Function

MsgBox ReverseCase("Hello VBScript")  ' 输出 hELLO vbsCRIPT

示例4:多参数、可选参数(VBScript 不支持真正可选参数,但可用 Empty 判断)

Function Greet(name, greeting)
    If IsEmpty(greeting) Then greeting = "你好"
    Greet = greeting & "," & name & "!"
End Function

MsgBox Greet("张三")                  ' 输出 你好,张三!
MsgBox Greet("李四", "Good morning")   ' 输出 Good morning,李四!

2. Sub(子程序)语法

用于执行操作,但不返回值。

语法

Sub 过程名(参数1, 参数2, ...)
    ' 代码块
End Sub

调用方式

  • Call 子程序名(参数)(带 Call 可省略括号)
  • 直接 子程序名 参数

示例1:弹出问候

Sub SayHello(name)
    MsgBox "Hello, " & name & "!今天是 " & Date()
End Sub

Call SayHello("王五")
' 或
SayHello "赵六"

示例2:批量删除文件(实用)

Sub DeleteFilesInFolder(folderPath)
    Dim fso, folder, file
    Set fso = CreateObject("Scripting.FileSystemObject")

    If fso.FolderExists(folderPath) Then
        Set folder = fso.GetFolder(folderPath)
        For Each file In folder.Files
            On Error Resume Next
            file.Delete True
            If Err.Number <> 0 Then
                MsgBox "删除失败:" & file.Name
                Err.Clear
            End If
        Next
        MsgBox "文件夹 " & folderPath & " 中的文件已清理!"
    Else
        MsgBox "文件夹不存在!"
    End If
End Sub

Call DeleteFilesInFolder("C:\Temp")

3. 参数传递方式(重要!)

VBScript 默认按引用传递(ByRef),即修改形参会影响实参。
想按值传递需显式用 ByVal

Sub Increment(ByRef num)
    num = num + 1
End Sub

Sub IncrementSafe(ByVal num)
    num = num + 1   ' 只修改副本,不影响原变量
End Sub

Dim x
x = 10
Call Increment(x)
MsgBox x   ' 输出 11(被修改了)

x = 10
Call IncrementSafe(x)
MsgBox x   ' 输出 10(未被修改)

4. 递归函数(函数调用自己)

VBScript 支持递归,常用于计算阶乘、斐波那契等。

示例:计算阶乘

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

MsgBox "5! = " & Factorial(5)   ' 输出 120

注意:递归层数太多可能导致栈溢出(一般几千层以内安全)。

5. 函数与 Sub 的结合使用(完整实用实例)

计算圆面积并显示结果。

Option Explicit

Const PI = 3.1415926

Function CircleArea(radius)
    CircleArea = PI * radius * radius
End Function

Sub ShowCircleInfo(radius)
    Dim area
    area = CircleArea(radius)
    MsgBox "半径:" & radius & vbCrLf & _
           "面积:" & FormatNumber(area, 2) & vbCrLf & _
           "周长:" & FormatNumber(2 * PI * radius, 2)
End Sub

Dim r
r = CDbl(InputBox("请输入圆的半径:"))
If r > 0 Then
    Call ShowCircleInfo(r)
Else
    MsgBox "半径必须大于0!"
End If

小结

  • 用 Function:需要返回值(如计算、判断、转换)
  • 用 Sub:只执行操作(如显示消息、删除文件、修改设置)
  • 永远加 Option Explicit
  • 注意参数传递方式(ByRef vs ByVal)
  • 函数名就是返回值变量
  • 可以嵌套、递归、互相调用

如果你有具体需求(如字符串处理函数、文件操作封装、数学计算函数等),告诉我,我可以为你写出完整可复用的函数代码!

文章已创建 3511

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部