8

I am just wondering how does an Or conditional statement work in VBA/VB6. Basically, if we have If A Or B Then, in what order are the Boolean expressions evaluated? If A is true, is B also evaluated?

Community
  • 1
  • 1
  • both will be evaluated regardless. In VBA I believe the only way around is to split them both into separated nested if statements. – Scott Craner Aug 20 '15 at 18:16
  • https://msdn.microsoft.com/EN-US/library/office/gg264205.aspx – findwindow Aug 20 '15 at 18:18
  • Previously: http://stackoverflow.com/questions/24641923/vba-short-circuit-and-alternatives , http://stackoverflow.com/questions/3242560/andalso-orelse-in-vba/3245183#3245183 – Tim Williams Aug 20 '15 at 18:48

1 Answers1

6

Here are some test results for you:

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

So, both expressions in an Or or an And are always evaluated, in order, regardless of outcome. You can use If ... Then If ... Then to achieve simple inline short-circuiting.

Bond
  • 16,071
  • 6
  • 30
  • 53