VBA Short-Circuit `And` Alternatives [duplicate]

As a more general apprach, I suggest to introduce condition flags and make usage of assigning comparison results to booleans:

dim cond1 as boolean
dim cond2 as boolean

cond1 = false
cond2 = false

' Step 1
cond1 = MyObj Is Nothing

' Step 2: do it only if step 1 was sucessful 
if cond1 then
    cond2 = MyObj.Property = 5
end if

' Final result:
if cond2 then
   msgbox "Yay"
else
   msgbox "Boo"
end if

By “chaining” those condition flags, every step is safe, you see the final result in the last condition flag and you don’t do unnecessary comparisons. And, to me, it keeps readable.

EDIT 2014-07-09

I usually never omit block delimiters and I consequently set every statement of control structures on a new line. But in this case, you can carefully get a very dense notation that reminds on short-circuit notation, also because the VBA compiler initiates the variables:

dim cond1 as boolean
dim cond2 as boolean
dim cond3 as boolean
dim cond4 as boolean

cond1 = MyObj Is Nothing
if cond1 then cond2 = MyObj.Property = 5
if cond2 then cond3 = MyObj.Property2 = constSomething
if cond3 then cond4 = not isNull(MyObj.Property77)

if cond4 then
   msgbox "Hyper-Yay"
else
   msgbox "Boo"
end if

I could agree to this. It’s a clear flow to read.

EDIT 2021-03-21

Thanks to @Tom’s comment, one can write it simpler:

dim cond as boolean

cond = MyObj Is Nothing
if cond then cond = MyObj.Property = 5
if cond then cond = MyObj.Property2 = constSomething
if cond then cond = not isNull(MyObj.Property77)

if cond then
   msgbox "Hyper-Yay"
else
   msgbox "Boo"
end if

@Tom explains the advantages in his comment below. I fully agree with this. I can only imagine some situations while debugging, when I would like to have separated results of the conditions, and therefore explicitely with four different variables.

Leave a Comment