在VBA(Visual Basic for Applications)中,条件语句用于根据一个或多个条件来执行不同的代码块。VBA提供了几种条件语句,如下所示:
一、If...Then 语句
1.1、基本形式(If...Then...Else...End If)
'If 条件 Then
'如果条件为真,则执行这里的代码
'Else
'如果条件为假,则执行这里的代码(可选)
'End If
Dim score As Integer
score = 85
If score >= 60 Then
MsgBox "及格"
Else
MsgBox "不及格"
End If
1.2、多条件判断语句(If...Then...ElseIf...Then...Else...End If )
'If 条件1 Then
'条件1为真时执行的代码
'ElseIf 条件2 Then
'条件1为假但条件2为真时执行的代码
'Else
'所有条件都为假时执行的代码(可选)
'End If
Dim score As Integer
score = 85
If score >= 90 Then
MsgBox "优秀"
ElseIf score >= 60 Then
MsgBox "及格"
Else
MsgBox "不及格"
End If
1.3、嵌套形式(即在一个If...Then
语句内部再包含一个或多个If...Then
语句)
'If 条件1 Then
'条件1为真时执行的代码
'If 条件2 Then
'条件1和条件2都为真时执行的代码
'Else
'条件1为真但条件2为假时执行的代码
'End If
'Else
'条件1为假时执行的代码
'End If
Dim score As Integer
score = 85
If score >= 60 Then
MsgBox "及格"
If score >= 90 Then
MsgBox "优秀"
Else
MsgBox "良好"
End If
Else
MsgBox "不及格"
End If
二、Select Case 语句
Select Case语句类似于其他编程语言中的Switch或Case语句,它允许你根据表达式的值来选择执行不同的代码块。
'Select Case 表达式
'Case 值1
'如果表达式 = 值1,则执行这里的代码
'Case 值2
'如果表达式 = 值2,则执行这里的代码
'可以有更多的 Case 分支
'Case Else
'如果表达式不匹配任何 Case 值,则执行这里的代码(可选)
'End Select
Dim dayOfWeek As Integer
dayOfWeek = 5
Select Case dayOfWeek
Case 1
MsgBox "星期一"
Case 2
MsgBox "星期二"
Case 3
MsgBox "星期三"
Case 4
MsgBox "星期四"
Case 5
MsgBox "星期五"
Case 6
MsgBox "星期六"
Case 7
MsgBox "星期日"
Case Else
MsgBox "无效的天数"
End Select
三、总结
在Select Case 语句中,你可以使用To关键字来表示一个范围,或者使用Is关键字来进行更复杂的比较(如比较字符串或日期)。条件语句是VBA编程中非常强大的工具,它们允许你根据程序运行时的不同情况来执行不同的代码路径。