AndAlso/OrElse In VBA


Answer :

The only short circuiting (of a sort) is within Case expression evaluation, so the following ungainly statement does what I think you're 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 

This is an old question, but this issue is still alive and well. One workaround I've used:

Dim success As Boolean       ' False by default.  If myObj Is Nothing Then     ' Object is nothing, success = False already, do nothing. ElseIf Not myObj.test() Then ' Test failed, success = False already, do nothing. Else: success = True         ' Object is not nothing and test passed. End If  If success Then     ' Do stuff... Else     ' Do other stuff... End If 

This basically inverts the logic in the original question, but you get the same result. I think it's a cleaner solution than the others here that only use If statements. The solution using a Select statement is clever, but if you want an alternative using only If statements, I think this is the one to use.


Or you could create a function that takes your object as a parameter and returns boolean for either case. That's what I usually to.

i.e.

if Proceed(objMyAwesomeObject) then        'do some really neat stuff here else        'do something else, eh end if ... end sub  private function Proceed(objMyAwesomeObject as Object)      if not objMyAweseomeObject is nothing then             Proceed = true      elseif objMyAwesomeObject.SomeProperty = SomeValue then             Proceed = true      else             Proceed = false      endif end function 

Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?