如何在VBA中评估Or语句?

时间:2015-08-20 18:10:33

标签: vba excel-vba if-statement conditional-statements excel

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

1 个答案:

答案 0 :(得分:5)

以下是您的一些测试结果:

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来实现简单的内联短路。