我正在编写一个VBA代码,如下所示:
If function_one Or Function_two Or Function_three Then
' Do Something
End If
因此,如果任何一个函数返回true值,它将执行某些操作。
我想,我写了一个小而有效的代码。
但是在调试期间我发现,VBA运行function_one,获取其返回值,然后运行function_two,获取其返回值,依此类推第三个,然后评估条件是否继续进行。
我想要实现的是,只要第一个函数返回true,它就应该执行某些操作,并且不应该执行其他函数。如果第一个函数失败,则只应调用下一个函数。
稍后,我使用循环关键字来完成此任务,但它看起来并不简单/聪明。 所以你知道,我怎么能用更优化的方式编写相同的代码。
答案 0 :(得分:2)
您必须手动实施短路:
result = function_one
if not result then
result = function_two
end if
if not result then
result = function_three
end if
If result Then
' Do Something
End If
VBA(和经典VB)不提供And
或Or
的短路版本(在VB.Net中,这些项目被引入为AndAlso
和{{1} })
答案 1 :(得分:1)
这应该更有效:
'define the do something function
If function_one Then
'do_something_function
ElseIf function_two Then
'do_something_function
Else function_three Then
'do_something_function
End If
离开你的预感,SBI。如果function_one为true,它应该执行do_something函数,而不检查其他函数。不过,我可能完全错了,因为我不在微软Office的电脑旁边。