目录
1. 条件语句概述
条件语句是程序中用于根据条件判断执行不同代码的控制结构。VBScript 提供了几种条件语句,最常见的包括 If...Then
、If...Then...Else
、Select Case
等。
这些语句允许程序根据不同的条件做出决策,确保程序执行的灵活性。
2. If…Then 语句
2.1 基本语法
1 2 3 | If condition Then ' 执行语句 End If |
2.2 示例
1 2 3 4 5 6 | Dim age age = 18 If age >= 18 Then MsgBox "You are an adult." End If |
该程序判断 age
是否大于或等于 18,如果是,则输出 “You are an adult.”。
3. If…Then…Else 语句
3.1 基本语法
1 2 3 4 5 | If condition Then ' 执行语句1 Else ' 执行语句2 End If |
3.2 示例
1 2 3 4 5 6 7 8 | Dim score score = 75 If score >= 60 Then MsgBox "You passed the exam." Else MsgBox "You failed the exam." End If |
该程序判断 score
是否及格(大于或等于 60),如果及格,则输出 “You passed the exam.”,否则输出 “You failed the exam.”。
4. If…Then…ElseIf…Else 语句
4.1 基本语法
1 2 3 4 5 6 7 | If condition1 Then ' 执行语句1 ElseIf condition2 Then ' 执行语句2 Else ' 执行语句3 End If |
4.2 示例
1 2 3 4 5 6 7 8 9 10 11 12 | Dim grade grade = "B" If grade = "A" Then MsgBox "Excellent" ElseIf grade = "B" Then MsgBox "Good" ElseIf grade = "C" Then MsgBox "Fair" Else MsgBox "Fail" End If |
该程序根据 grade
的值输出不同的评价。
5. Select Case 语句
5.1 基本语法
1 2 3 4 5 6 7 8 | Select Case expression Case value1 ' 执行语句1 Case value2 ' 执行语句2 Case Else ' 执行语句3 End Select |
5.2 示例
1 2 3 4 5 6 7 8 9 10 11 12 13 | Dim grade grade = "B" Select Case grade Case "A" MsgBox "Excellent" Case "B" MsgBox "Good" Case "C" MsgBox "Fair" Case Else MsgBox "Fail" End Select |
该程序通过 Select Case
语句判断 grade
,并根据不同的值输出对应的消息。
6. 条件语句使用示例
6.1 检查温度范围
1 2 3 4 5 6 7 8 9 10 11 12 | Dim temperature temperature = 25 If temperature < 0 Then MsgBox "It's freezing!" ElseIf temperature >= 0 And temperature <= 20 Then MsgBox "It's cold!" ElseIf temperature > 20 And temperature <= 30 Then MsgBox "It's warm!" Else MsgBox "It's hot!" End If |
该程序根据温度值判断并输出相应的天气描述。
6.2 判断用户输入
1 2 3 4 5 6 7 8 | Dim userAge userAge = InputBox("Enter your age:") If userAge >= 18 Then MsgBox "You are eligible to vote." Else MsgBox "You are not eligible to vote." End If |
该程序通过 InputBox
获取用户输入的年龄并判断是否满足投票年龄。
发表回复