VB 关键字

保留字、语句关键字、运算符与常量分类速查。

Intermediate
Key PointsVBScript 的关键字分四类:声明、流程、过程、错误处理,加上运算符和内置常量。

声明

KeywordUse
DimDim x, y
ReDimReDim Preserve a(10)
ConstConst PI = 3.14
Option Explicit文件第一行
Public / Private在类或模块里用
ClassClass Foo ... End Class

流程

KeywordUse
If ... Then ... ElseIf ... Else ... End If多分支判断
Select Case ... End Select按值分派
For ... NextFor i = 1 To 10 Step 2
For Each ... NextFor Each x In arr
Do While ... Loop先判断
Do ... Loop Until先执行
While ... Wend不推荐
Exit For / Exit Do只跳一层

过程

KeywordUse
Sub ... End Sub不返回值
Function ... End Function返回值
CallCall F(a)
ByValSub F(ByVal x)
ByRef默认行为
OptionalFunction F(a, Optional b = 1)
Exit Sub / Exit Function唯一的退出方式

错误处理

VBSCRIPT
On Error Resume Next          ' 出错继续
' ... 可能出错的代码 ...
If Err.Number <> 0 Then
    WScript.Echo Err.Number & ":" & Err.Description
    Err.Clear                 ' 清空错误
End If
On Error GoTo 0               ' 恢复正常错误处理
KeywordUse
On Error Resume Next跳过错误语句继续
On Error GoTo 0关闭忽略
ErrNumber、Description、Source
Err.Clear清空当前错误

运算符

CategoryOperators
Arithmetic+ - * / \(整除) Mod ^
Comparison= <> < > <= >= Is
LogicAnd Or Not Xor Eqv Imp
Concat&
Other.(成员) ()(调用)
VBSCRIPT
WScript.Echo 7 \ 2          ' 3(整除)
WScript.Echo 7 Mod 2        ' 1(余数)
WScript.Echo 2 ^ 10         ' 1024
WScript.Echo "a" & "b"      ' ab
WScript.Echo Not True       ' False
Output
3
1
1024
ab
False

\ is integer division and / floating: 7 / 2 is 3.5, 7 \ 2 is 3. Programmers from C-family languages often expect / to truncate and get a decimal instead.

内置常量

GroupConstants
MsgBox buttonsvbOKOnly(0) vbOKCancel(1) vbYesNo(4) vbYesNoCancel(3)
MsgBox returnvbOK(1) vbCancel(2) vbYes(6) vbNo(7)
MsgBox iconvbCritical(16) vbQuestion(32) vbExclamation(48) vbInformation(64)
StringvbCr vbLf vbCrLf vbTab vbNullChar
ComparevbBinaryCompare(0) vbTextCompare(1)
DatevbSunday(1) vbMonday(2) ... vbUseSystemDayOfWeek(0)
ColorvbRed vbGreen vbBlue vbBlack vbWhite

保留字不能当变量名

VBSCRIPT
' 错误:这些是保留字
' Dim date        ' Date 是函数名,虽然能过编译但会遮蔽函数
' Dim len         ' 同上
' Dim if          ' 语法错误

' 安全做法:加前缀或改词
Dim dToday
Dim nLength
Dim sName
Names like Date, Len, Time and Name are usable as variables but shadow the function of the same name, so Date() later returns your variable. Such bugs are painful; a type prefix (d, n, s) avoids them entirely.

语句分隔

VBSCRIPT
Dim a, b
a = 1 : b = 2 : WScript.Echo a + b

If a > 0 Then WScript.Echo "正" : WScript.Echo "数"
' 上面这行:单行 If 只作用于第一条语句,第二条总会执行
Output
3
正
数

Colons separate statements on one line, but with a single-line If only the first is conditional — the rest always run. Very easy to misread; avoid colons in real code.

Friends & Partners