【问题标题】:How is an Or statement evaluated in VBA?如何在 VBA 中评估 Or 语句?
【发布时间】:2015-11-14 12:26:03
【问题描述】:

我只是想知道Or 条件语句在 VBA/VB6 中是如何工作的。基本上,如果我们有If A Or B Then,布尔表达式的求值顺序是什么?如果 A 为真,是否也评估 B?

【问题讨论】:

标签: vba excel if-statement conditional-statements


【解决方案1】:

以下是一些测试结果:

Public Sub DoTesting()

    ' Displays "Test1" followed by "Test2", so they're evaluated in order.
    ' Also, both expressions are evaluated even though Test1() is False.
    If Test1() And Test2() Then
    End If

    ' Displays "Test2" followed by "Test1", so they're evaluated in order.
    ' Also, both expressions are evaluated even though Test2() is True.
    If Test2() Or Test1() Then
    End If

    ' Displays "Test1" only. Test2() is not evaluated.
    If Test1() Then If Test2() Then Debug.Print ""

End Sub

Public Function Test1() As Boolean
    MsgBox "Test1"
    Test1 = False
End Function

Public Function Test2() As Boolean
    MsgBox "Test2"
    Test2 = True
End Function

因此,无论结果如何,OrAnd 中的两个表达式总是按顺序计算。您可以使用If ... Then If ... Then 来实现简单的内联短路。

【讨论】:

    猜你喜欢
    • 2015-03-22
    • 1970-01-01
    • 2010-12-01
    • 2013-11-04
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多