If 是 VBScript 最基礎、最常用的流程控制結構,分為單行、區塊與巢狀三種形式,靈活應對各種雙分支決策需求。
If <條件> Then [<陳述句1>] [Else <陳述句2>]
: 分隔:If x > 0 Then y = 1 : z = 2 Else y = -1 : z = -2。Else 為選用;省略時條件為假不執行任何動作。<html>
<head><title>單行 If 範例</title></head>
<body>
<script language="VBScript" for="button1" event="onClick">
Dim myWeek, a
myWeek = WeekDay(Now) - 1 ' 0=週日, 1=週一...
If myWeek = 0 Then a = "要好好休息喲。" Else a = "努力工作呀!"
MsgBox "今天是星期" & myWeek & "," & a
</script>
<center><input type="button" name="button1" value="請查看今天是星期幾"></center>
</body>
</html>
If <條件> Then
[陳述句區塊1]
[Else
[陳述句區塊2]]
End If
End If 必須配對,否則編譯錯誤。<html>
<head><title>區塊 If 範例</title></head>
<body>
<script language="VBScript" for="button1" event="onClick">
Dim a, b
a = Text1.Value
If Not IsNumeric(a) Then
MsgBox "您輸入的不是數值資料"
Else
b = "您輸入的資料是:" & a & ", 它的平方根是:" & Sqr(a)
MsgBox b, , "求一個數的平方根"
End If
</script>
<center>請輸入數值資料:<input type="text" name="text1" size="10">
<input type="button" name="button1" value="求一個數的平方根"></center>
</body>
</html>
Then 或 Else 區塊內再包含 If。Select Case、函式拆解或查表法。If 必須有對應的 End If,縮排對齊是閱讀關鍵。<html>
<head><title>託運費計算</title></head>
<body>
請輸入行李重量:<input name="text2" type="text" size="10"> kg
<input type="button" name="button3" value="計算運費">
<script language="VBScript" for="button3" event="onClick">
Dim w, x
w = text2.Value
If Not IsNumeric(w) Then
MsgBox "您輸入的不是數值資料"
Else
If w <= 50 Then
x = 0.5 * w
Else
If w <= 100 Then
x = 0.5 * 50 + 1.5 * (w - 50)
Else
x = 0.5 * 50 + 1.5 * 50 + 2 * (w - 100)
End If
End If
MsgBox "行李的託運費是:" & x & "元", , "計算行李費"
End If
</script>
</body>
</html>
費率邏輯:
| 情境 | 建議寫法 | 理由 |
|---|---|---|
| 單一簡短陳述句 | 單行 If | 簡潔、一目瞭然 |
| 分支超過 1 行或含迴圈/函式呼叫 | 區塊 If | 結構清晰、易除錯 |
| 同一變數對比多個離散值/區間 | Select Case / Select Case True | 效能佳、可讀性高 |
| 巢狀超過 3 層 | 重構:函式、查表、狀態機 | 降低認知負荷、減少 Bug |
| 條件為「非數值」防呆 | 優先 If Not IsNumeric(x) Then ... Else ... | 及早攔截、避免型別錯誤 |
If "A" = "a" 為 False(預設 Binary 比較),需 Option Compare Text 或 UCase/LCase 正規化。If var > 0 若 var 為 Null 會拋錯,先用 IsNull 或 VarType 檢查。If 0.1 + 0.2 = 0.3 可能為 False,建議 Abs(a - b) < 0.0001 判斷近似相等。熟練駕馭 If 三種形式,能讓您精準表達任何雙分支決策邏輯,寫出強健的 VBScript 程式。