首页 > 解决方案 > 为什么在“或”不起作用时“与”在这里起作用?

问题描述

在我的情况下,使用 OR 不起作用,我必须使用 AND,我不知道为什么。

Sub blah()
    If LCase(Environ("username")) <> "me" Or LCase(Environ("username")) <> "some other user" Then '''DOESN'T WORK
        Stop
    ElseIf LCase(Environ("username")) <> "me" And LCase(Environ("username")) <> "some other user" Then  '''WORKS
        Stop
    End If
End Sub

标签: excelvba

解决方案


您的示例很难理解,但您可能只是对运算符的性质感到困惑。

想想真值表;操作的结果OrTrue如果至少有一个操作数是True

True Or True   => True
True Or False  => True
False Or True  => True
False Or False => False

同样,如果两个操作数都是,则And运算的结果是:TrueTrue

True And True   => True
True And False  => False
False And True  => False
False And False => False

如果有帮助,您可以将其可视Or化为+(加法)和And*乘法)运算,其中False存在0True“不为零”:

1 Or 1 => 1 + 1 => True
1 Or 0 => 1 + 0 => True
0 Or 1 => 0 + 1 => True
0 Or 0 => 0 + 0 => False

1 And 1 => 1 * 1 => True
1 And 0 => 1 * 0 => False
0 And 1 => 0 * 1 => False
0 And 0 => 0 * 0 => False

推荐阅读