Function Foo(thiscell As Range) As Boolean
Foo = thiscell.hasFormula And (InStr(1, UCase(Split(thiscell.formula, Chr(40))(0)), "bar") > 0)
End Function此函数用于测试(之前是否存在某个子字符串(在本例中为bar)。
我遇到的问题是,当传递给函数的单元格为空时,thisCell.hasFormula为false,但and后面的语句仍在计算中。这在运行时给了我一个下标超出范围的错误。
VBA是否真的继续计算And的第二个参数,即使第一个参数为false?
发布于 2011-08-11 02:03:36
您正在寻找的是名为"short-circuit evaluation“的软件。
VBA没有。
您可以看到一种可能适用于您的情景here的方法。
在那里选择的方法包括用Select Case替换If。还有一个使用嵌套Ifs的示例。
发布于 2011-08-11 11:29:34
作为DOK mentioned:不,VBA没有短路评估。
从技术上讲,使用2个If-then语句比使用AND运算符更有效,但除非您经常这样做,否则您不会注意到节省的空间,所以请选择可读性更好的语句。如果你想获得真正的技术支持,VBA处理多个If-then语句的速度也比Select Case更快。
VBA很奇怪:)
发布于 2013-05-11 07:26:59
答案是肯定的,VBA不会短路求值。
这不仅仅是风格的问题;在这样的情况下会有很大的不同:
If i <= UBound(Arr, 1) And j <= UBound(Arr, 2) And Arr(i, 1) <= UBound(Arr2, 1) Then
Arr2(Arr(i, 1), j) = Arr(i, j)
End If...which不正确。更恰当的说法是:
If i <= UBound(Arr, 1) And j <= UBound(Arr, 2) Then
If Arr(i, 1) <= UBound(Arr2, 1) Then
Arr2(Arr(i, 1), j) = Arr(i, j)
End If
End If或者如果你不喜欢嵌套的if:
If i > UBound(Arr, 1) Or j > UBound(Arr, 2) Then
' Do Nothing
ElseIf Arr(i, 1) > UBound(Arr2, 1) Then
' Do Nothing
Else
Arr2(Arr(i, 1), j) = Arr(i, j)
End Ifhttps://stackoverflow.com/questions/7015471
复制相似问题