VB 条件

If / ElseIf / Select Case、逻辑运算符与真假判断。

Beginner
Key Points条件用 If...Then...ElseIf...Else...End If 或 Select Case;VBScript 里 0 为假,非 0 为真。

If

VBSCRIPT
Dim score
score = 85

If score >= 90 Then
    WScript.Echo "优秀"
ElseIf score >= 60 Then
    WScript.Echo "及格"
Else
    WScript.Echo "不及格"
End If
Output
及格

ElseIf is one word, not Else If. Two words is a syntax error in VBScript — a common slip for people coming from VB.NET, which accepts both.

单行 If

VBSCRIPT
Dim x
x = 5

If x > 0 Then WScript.Echo "正数"
If x > 0 Then WScript.Echo "正数" Else WScript.Echo "非正数"
Output
正数
正数

The single-line form takes no End If and only one statement. Beyond that use the block form; joining statements with : in a single-line If behaves unpredictably.

Select Case

VBSCRIPT
Dim code
code = "B"

Select Case code
    Case "A"
        WScript.Echo "优秀"
    Case "B", "C"
        WScript.Echo "良好"
    Case "D"
        WScript.Echo "及格"
    Case Else
        WScript.Echo "不及格"
End Select
Output
良好

Case "B", "C" matches several values in one branch. Select Case reads better than a chain of ElseIf and evaluates the expression once, whereas each ElseIf re-evaluates it.

区间与比较

VBSCRIPT
Dim n
n = 75

Select Case True                 ' 常用技巧:用 True 做区间判断
    Case n >= 90
        WScript.Echo "A"
    Case n >= 60
        WScript.Echo "B"
    Case Else
        WScript.Echo "C"
End Select
Output
B

VBScript's Select Case has no Case 60 To 89 range syntax (that is VB.NET). Select Case True with boolean expressions achieves the same and appears often in legacy code.

逻辑运算符

VBSCRIPT
Dim a, b
a = True : b = False

WScript.Echo a And b        ' False
WScript.Echo a Or b         ' True
WScript.Echo Not a          ' False
WScript.Echo a Xor b        ' True
WScript.Echo (1 = 1) And (2 > 1)     ' True
Output
False
True
False
True
True

And / Or do not short-circuit: both sides are evaluated. So If obj Is Nothing Or obj.Name = "" Then still touches obj.Name when obj is Nothing and fails. Nest the Ifs instead.

真假判断

VBSCRIPT
If 0 Then WScript.Echo "0 为真" Else WScript.Echo "0 为假"
If 1 Then WScript.Echo "1 为真"
If -1 Then WScript.Echo "-1 为真"
If "" Then WScript.Echo "空串为真" Else WScript.Echo "空串为假"
Output
0 为假
1 为真
-1 为真
空串为假

Numeric 0 is false and any non-zero value true (including -1). Empty strings are false. Null makes the whole condition Null, so If Null Then takes the Else branch — a frequent source of subtle bugs.

A value from a database or Request may be the string "0", which is true in an If (non-empty string). Convert with CInt first, or If Request("flag") Then enters the true branch for "0".

Friends & Partners