并且在VBA中也是/ OrElse

Lui*_*uis 42 vb.net vba

我正在尝试通过执行以下操作在Excel宏中使用"和"进行惰性评估:

If Not myObject Is Nothing *And* myObject.test() Then
    'do something'
Else
    'do something else'
End If
Run Code Online (Sandbox Code Playgroud)

我知道在VB.NET中存在懒惰的评估AndAlso,OrElse但在VBA中找不到类似的东西.如果VBA中不存在惰性求值,那么构造代码的最佳方法是什么,以便评估我期望的方式?

Ale*_* K. 51

唯一的短路(一种)是在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
Run Code Online (Sandbox Code Playgroud)

  • @Wildhorn:“而不是从右到左” - 听起来好像 VB.NET 中的“OrElse”从右到左评估条件。这是你的意思吗?因为我认为情况并非如此 (5认同)

nei*_*zan 11

这是一个老问题,但这个问题仍然存在并且很好.我使用过的一种解决方法:

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
Run Code Online (Sandbox Code Playgroud)

这基本上颠倒了原始问题中的逻辑,但是你得到了相同的结果.我认为这是一个比其他人更清晰的解决方案,只使用If语句.使用Select语句的解决方案很聪明,但是如果你想要只使用If语句的替代方案,我认为这是一个使用的方法.