一、VBScript基础概念
VBScript(Visual Basic Scripting Edition)是一种脚本语言,主要用于:
- Windows系统管理
- ASP网页开发
- Office自动化
- 简单的桌面程序
二、基础语法实例
1. 第一个VBScript程序
' 注释:使用MsgBox显示消息
MsgBox "Hello VBScript!", vbInformation, "欢迎"
2. 变量和数据类型
' 声明变量
Dim name, age, salary
Dim isMarried
' 赋值
name = "张三"
age = 25
salary = 5000.50
isMarried = False
' 输出
MsgBox "姓名:" & name & vbCrLf & _
"年龄:" & age & vbCrLf & _
"工资:" & salary
3. 输入输出
' 输入框
Dim userName
userName = InputBox("请输入您的姓名:", "输入")
If userName <> "" Then
MsgBox "您好," & userName & "!"
End If
4. 条件语句
' If...Then...Else
Dim score
score = InputBox("请输入分数:")
If IsNumeric(score) Then
score = CInt(score)
If score >= 90 Then
MsgBox "优秀"
ElseIf score >= 60 Then
MsgBox "及格"
Else
MsgBox "不及格"
End If
Else
MsgBox "请输入数字!"
End If
5. 循环语句
' For循环
Dim i, sum
sum = 0
For i = 1 To 10
sum = sum + i
Next
MsgBox "1到10的和是:" & sum
' While循环
Dim count
count = 1
Do While count <= 5
MsgBox "第" & count & "次循环"
count = count + 1
Loop
' Do Until循环
Dim num
num = 1
Do Until num > 3
MsgBox "当前数字:" & num
num = num + 1
Loop
6. 数组
' 声明数组
Dim fruits(3)
fruits(0) = "苹果"
fruits(1) = "香蕉"
fruits(2) = "橙子"
fruits(3) = "葡萄"
' 遍历数组
Dim output, index
output = "水果列表:" & vbCrLf
For index = 0 To UBound(fruits)
output = output & (index + 1) & ". " & fruits(index) & vbCrLf
Next
MsgBox output
' 动态数组
Dim numbers()
ReDim numbers(5)
Dim j
For j = 0 To 5
numbers(j) = j * 10
Next
' 重新调整大小,保留原有数据
ReDim Preserve numbers(10)
7. 过程与函数
' Sub过程(无返回值)
Sub Greet(name)
MsgBox "你好," & name & "!"
End Sub
' 调用过程
Call Greet("李四")
' Function函数(有返回值)
Function Add(a, b)
Add = a + b
End Function
' 调用函数
Dim result
result = Add(10, 20)
MsgBox "10 + 20 = " & result
' 计算阶乘的函数
Function Factorial(n)
If n <= 1 Then
Factorial = 1
Else
Factorial = n * Factorial(n - 1)
End If
End Function
MsgBox "5的阶乘是:" & Factorial(5)
8. 字符串操作
Dim str1, str2, length, upperStr, lowerStr
str1 = "Hello "
str2 = "VBScript"
' 连接字符串
Dim combined
combined = str1 & str2
MsgBox combined
' 获取长度
length = Len(combined)
MsgBox "字符串长度:" & length
' 大小写转换
upperStr = UCase(combined)
lowerStr = LCase(combined)
MsgBox "大写:" & upperStr & vbCrLf & "小写:" & lowerStr
' 截取字符串
Dim part
part = Mid(combined, 7, 4)
MsgBox "第7-10个字符:" & part
' 查找字符串
Dim position
position = InStr(combined, "Script")
MsgBox "Script的位置:" & position
' 替换
Dim newStr
newStr = Replace(combined, "Hello", "Hi")
MsgBox "替换后:" & newStr
9. 日期和时间
' 获取当前日期时间
Dim currentTime
currentTime = Now
MsgBox "当前时间:" & currentTime
' 获取日期部分
Dim currentDate
currentDate = Date
MsgBox "当前日期:" & currentDate
' 格式化日期
MsgBox "年:" & Year(currentDate) & vbCrLf & _
"月:" & Month(currentDate) & vbCrLf & _
"日:" & Day(currentDate) & vbCrLf & _
"星期:" & WeekdayName(Weekday(currentDate))
' 日期计算
Dim tomorrow, nextWeek
tomorrow = DateAdd("d", 1, currentDate)
nextWeek = DateAdd("d", 7, currentDate)
MsgBox "明天:" & tomorrow & vbCrLf & _
"一周后:" & nextWeek
10. 文件操作
' 创建文件系统对象
Dim fso, file, folder, text
Set fso = CreateObject("Scripting.FileSystemObject")
' 创建文件夹
If Not fso.FolderExists("C:\TestFolder") Then
Set folder = fso.CreateFolder("C:\TestFolder")
MsgBox "文件夹创建成功"
End If
' 创建文件
Set file = fso.CreateTextFile("C:\TestFolder\test.txt", True)
' 写入文件
file.WriteLine "第一行"
file.WriteLine "第二行"
file.Close
' 读取文件
Set file = fso.OpenTextFile("C:\TestFolder\test.txt", 1)
text = file.ReadAll
file.Close
MsgBox "文件内容:" & vbCrLf & text
' 删除文件
fso.DeleteFile "C:\TestFolder\test.txt"
fso.DeleteFolder "C:\TestFolder"
11. 错误处理
On Error Resume Next ' 启用错误处理
Dim x, y, z
x = 10
y = 0
' 这里会产生除以零的错误
z = x / y
If Err.Number <> 0 Then
MsgBox "错误号:" & Err.Number & vbCrLf & _
"错误描述:" & Err.Description & vbCrLf & _
"错误来源:" & Err.Source
Err.Clear ' 清除错误
Else
MsgBox "结果:" & z
End If
On Error GoTo 0 ' 禁用错误处理
12. 实用示例:学生成绩管理系统
' 学生成绩管理
Dim students(2, 2) ' 3个学生,3门课程
' 初始化成绩
students(0, 0) = "张三"
students(0, 1) = 85
students(0, 2) = 90
students(1, 0) = "李四"
students(1, 1) = 75
students(1, 2) = 80
students(2, 0) = "王五"
students(2, 1) = 95
students(2, 2) = 88
' 显示所有学生成绩
Dim outputStr, i
outputStr = "学生成绩表:" & vbCrLf & vbCrLf
outputStr = outputStr & "姓名 语文 数学 平均分" & vbCrLf
outputStr = outputStr & "--------------------------" & vbCrLf
For i = 0 To 2
Dim avgScore
avgScore = (students(i, 1) + students(i, 2)) / 2
outputStr = outputStr & students(i, 0) & " " & _
students(i, 1) & " " & _
students(i, 2) & " " & _
FormatNumber(avgScore, 1) & vbCrLf
Next
MsgBox outputStr
三、运行VBScript的方法
1. 保存为文件
将代码保存为 .vbs 文件,双击运行。
2. 在命令行运行
cscript script.vbs
wscript script.vbs
3. 在HTML中嵌入
<html>
<body>
<script type="text/vbscript">
MsgBox "这是网页中的VBScript"
</script>
</body>
</html>
四、调试技巧
' 使用MsgBox调试
Dim debugValue
debugValue = 100
MsgBox "调试点1:debugValue = " & debugValue
' 使用WScript.Echo(在命令行显示)
WScript.Echo "调试信息"
' 使用日志文件
Dim logFile
Set logFile = CreateObject("Scripting.FileSystemObject").CreateTextFile("debug.log", True)
logFile.WriteLine "程序开始运行:" & Now
logFile.Close
五、最佳实践
变量命名:使用有意义的名称
添加注释:解释复杂逻辑
错误处理:总是包含错误处理代码
代码缩进:保持代码整洁
模块化:将功能封装成过程和函数
这个教程涵盖了VBScript的主要基础语法,通过实例学习可以更快掌握。建议从简单的例子开始,逐步尝试更复杂的功能。