EP01. “Logical Operators 逻辑运算符”
🔒 登录后可标记已读- 这篇介绍 VBA
If Then语句常搭配的三个逻辑运算符:And、Or、Not - 用来把多个判断条件组合在一起
- 前置知识是基本的
If Then Else语法 - 学完能写出「同时满足两个条件」「满足其中一个条件」「排除某个条件」这类判断逻辑
重点内容
适用版本
桌面版通用(Excel 365 / 2021 / 2019 等)。
And 运算符
场景:A1 存 score1,B1 存 score2,score1 ≥ 60 而且 score2 > 1 才算 pass,否则 fail。
Dim score1 As Integer, score2 As Integer, result As String
score1 = Range("A1").Value
score2 = Range("B1").Value
If score1 >= 60 And score2 > 1 Then
result = "pass"
Else
result = "fail"
End If
Range("C1").Value = result
运行结果:如果 score2 不大于 1,即使 score1 ≥ 60,And 两边条件没有同时成立,结果还是返回 "fail"。
Or 运算符
把上面的 And 换成 Or,只要 score1 ≥ 60 或 score2 > 1 其中一个成立就算 pass:
Dim score1 As Integer, score2 As Integer, result As String
score1 = Range("A1").Value
score2 = Range("B1").Value
If score1 >= 60 Or score2 > 1 Then
result = "pass"
Else
result = "fail"
End If
Range("C1").Value = result
运行结果:只要 score1 ≥ 60 这一个条件成立,就算 score2 不大于 1,结果依然返回 "pass"。
Not 运算符
Not 用来反转一个条件的真假,比如「score2 不等于 1」:
Dim score1 As Integer, score2 As Integer, result As String
score1 = Range("A1").Value
score2 = Range("B1").Value
If score1 >= 60 And Not score2 = 1 Then
result = "pass"
Else
result = "fail"
End If
Range("C1").Value = result
运行结果:如果 score2 正好等于 1,Not score2 = 1 变成 False,即使 score1 ≥ 60,整个条件也不成立,结果返回 "fail"。
方法怎么选
| 情境 | 用哪个 | 备注 |
|---|---|---|
| 两个条件都要成立才算真 | And | 例如 score1 ≥ 60 而且 score2 > 1 |
| 满足其中一个条件就算真 | Or | 例如 score1 ≥ 60 或 score2 > 1 其中一个成立 |
| 要反转某个条件的真假 | Not | 例如判断 score2 不等于 1 |
怎么运行
把代码贴进 VBA 编辑器(Developer → Visual Basic,或 Alt + F11)对应的模块或按钮事件里,按 F5 或点命令按钮执行,结果会写入 C1。
学完你会
- ✅ 用
And写出「两个条件都要成立」的判断 - ✅ 用
Or写出「满足其中一个条件就好」的判断 - ✅ 用
Not反转条件的真假
常见错误
- 把
And和Or用反——And要求两个条件都成立才算真,Or只要一个成立就算真,混用会导致判断结果完全相反 Not后面接的条件式要注意运算符优先级,最好用括号把要反转的条件包起来,避免 VBA 按非预期顺序解析- 中文版 Excel 里 VBA 编辑器菜单是英文的,不受 Excel 界面语言影响,不用担心「翻译版函数名」的问题
Sources
Blog / Website: