为了账号安全,请及时绑定邮箱和手机立即绑定

VBA中的AndAlso / OrElse

VBA中的AndAlso / OrElse

子衿沉夜 2019-11-19 10:22:32
我正在尝试通过执行以下操作在Excel宏中使用'And'进行惰性评估:If Not myObject Is Nothing *And* myObject.test() Then    'do something'Else    'do something else'End If我知道VB.NET中存在惰性评估AndAlso,OrElse但是在VBA中找不到类似的评估。如果VBA中不存在惰性评估,那么构造代码的最佳方法是什么,以便它将评估我期望的方式?
查看完整描述

3 回答

?
慕标5832272

TA贡献1966条经验 获得超4个赞

唯一的短路(某种程度上)是在Case表达式求值内,因此以下令人费解的语句可以满足我的要求。


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


查看完整回答
反对 回复 2019-11-19
?
RISEBY

TA贡献1856条经验 获得超5个赞

这是一个古老的问题,但是这个问题仍然存在。我使用的一种解决方法:


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

这基本上颠倒了原始问题的逻辑,但是您得到的结果相同。我认为这是一个比仅使用If语句的解决方案更干净的解决方案。使用Select语句的解决方案很聪明,但是如果您只想使用If语句来替代,我认为这是可以使用的解决方案。


查看完整回答
反对 回复 2019-11-19
?
潇湘沐

TA贡献1816条经验 获得超6个赞

或者,您可以创建一个将对象作为参数并返回布尔值的函数。那就是我通常的目的。



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


查看完整回答
反对 回复 2019-11-19
  • 3 回答
  • 0 关注
  • 630 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信