tags:

views:

68

answers:

2

Hey I'm trying to get a lazy evaluation 'And' in my my Excel macro to do something like:


If Not myObject Is Nothing *And* myObject.test() Then
    'do something'
Else
    'do something else'
End If

I know this exists in VB.NET as AndAlso and OrElse but cannot find anything similar in VBA. If this actually does not exist what's the best way to structure this?

A: 
If Not myObject Is Nothing Then
    If myObject.test() Then
        'do something'
    End If
Else
   'do something else'
End If

I think that's the way you have to do it.

Edit

Maybe like this

Dim bTestsFailed as Boolean
bTestsFailed = False

If Not myObject Is Nothing Then
    If myObject.test() Then
        'do something'
    Else
        bTestsFailed = True
    End If
Else
   bTestsFailed = True
End If

If bTestsFailed Then
    'do something else
End If

Isn't VBA great?

Dick Kusleika
I think he wants to have the else condition also execute if myObject Is Nothing, meaning you have to duplicate the `Else 'do something else'`.
BenV
@BenV, @Dick I took the liberty of editing the answer to (I believe) the correct code. I agree with BenV
MarkJ
@MarkJ: I think he also wants `something else` to happen if myObject is not Nothing but `myObject.test()` returns False.
BenV
Thanks everyone, you're right I needed the code to execute if either was false. This works but it's a bit ugly me thinks; I like the 'Select Case' solution instead for cleanliness.
Luis
Yeah, I like Select Case too. I never thought of doing it that way, but it's much cleaner.
Dick Kusleika
+2  A: 

The only short circuiting (of a sort) is within Case expression evaluation, so the following ungainly statement does what I think your asking;

Select Case True
    Case (myObject Is Nothing), Not myObject.test()
        MsgBox "no instance or test == false"
    Case Else
        MsgBox "got instance & test == true"
    End Select
End Sub
Alex K.