Microsoft Lab
全部软件
Excel条件判断(If Then Statement)约 6 分钟

Logical Operators 逻辑运算符

重点内容


适用版本

桌面版通用(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 用反——And 要求两个条件都成立才算真,Or 只要一个成立就算真,混用会导致判断结果完全相反
  • Not 后面接的条件式要注意运算符优先级,最好用括号把要反转的条件包起来,避免 VBA 按非预期顺序解析
  • 中文版 Excel 里 VBA 编辑器菜单是英文的,不受 Excel 界面语言影响,不用担心「翻译版函数名」的问题

Sources

Blog / Website:

  1. Logical Operators
只记在你的浏览器里,换设备不会同步。