order of evaluation

P

Paul Pedersen

I have a statement like this:

If condition1 Or condition2 Or condition3 Then
blah blah
End If

In situations in which condition2 will not evaluate, an error is raised even
if condition1 evaluates to True (at which point conditions 2 and 3 are
irrelevant, so there's no point in attempting to evaluate them).

Is it wrong to assume that conditions will be evaluated in the order in
which they are presented?
 
N

NickHK

Paul,
A Select Case will stop evaluation when a matching Case is found. So this
will run:

Private Sub CommandButton2_Click()
Dim MyObj As Object

Select Case True
Case 1 = 1
Case MyObj.Value = 23
Case Else
End Select

End Sub

but this will fail:


Private Sub CommandButton2_Click()
Dim MyObj As Object

Select Case True
Case MyObj.Value = 23
Case 1 = 1
Case Else
End Select

End Sub

NickHK
 
J

John Coleman

Nick,

Clever work-around to VBA's lack of short-circuit Boolean evaluation.
I'm sure I'll use it sooner or later. To make it work in general might
require the dreaded goto statement (if "blah,blah" is a sizable code
block):

Sub test()
Select Case True
Case 0 = 1: GoTo ifTrue
Case 1 = 1: GoTo ifTrue 'True!
Case 0 = 1 / 0: GoTo ifTrue '0 = 1/0 is never evaluated! So no
div by 0 error
Case Else
MsgBox "Can skip this of course"
End Select
GoTo done
ifTrue:
MsgBox "blah, blah"
done:
MsgBox "rest of program goes here"

End Sub

This is functionally equivalent to:

Sub test2()
If 0 = 1 Then
GoTo ifTrue
ElseIf 1 = 1 Then
GoTo ifTrue
ElseIf 0 = 1 / 0 Then
GoTo ifTrue
Else
MsgBox "Can skip this of course"
End If
GoTo done
ifTrue:
MsgBox "blah, blah"
done:
MsgBox "rest of program goes here"
End Sub

Probably you can come up with a deeply nested if construct to avoid
the gotos (without having to repeat the statements to be executed) but
it is not clear that it would be any more readable.

-John Coleman
 
P

Paul Pedersen

Thanks.


NickHK said:
Paul,
A Select Case will stop evaluation when a matching Case is found. So this
will run:

Private Sub CommandButton2_Click()
Dim MyObj As Object

Select Case True
Case 1 = 1
Case MyObj.Value = 23
Case Else
End Select

End Sub

but this will fail:


Private Sub CommandButton2_Click()
Dim MyObj As Object

Select Case True
Case MyObj.Value = 23
Case 1 = 1
Case Else
End Select

End Sub

NickHK
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top