Reputation: 1175
I am writing a VBA code which looks as follows:
If function_one Or Function_two Or Function_three Then
' Do Something
End If
So, if any one of the functions return true value, it will do something.
I thought, I have written a small, and efficient code.
But during debugging I found, VBA runs function_one, gets its return value, then runs function_two, gets its return value, and so on for third and then evaluates if condition and proceeds further.
What I want to achieve is, as soon as first function returns true it should do something, and should not execute other functions. If first function fails then only next function should be called.
Later on, I used loop keywords to achieve this task, but it doesn't looks simple/smart. So do you know, how I could write, same code in more optimized way.
Upvotes: 1
Views: 218
Reputation: 239664
You have to implement short-circuiting by hand:
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 (and classic VB) doesn't offer short-circuiting versions of And
or Or
(In VB.Net, such items were introduced as AndAlso
and OrElse
)
Upvotes: 2
Reputation: 7922
This should be more efficient:
'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
Going off of your hunch, SBI. It should do the do_something function if function_one is true, and not check the others. I could be totally wrong, though, as I am not near my computer with Microsoft Office.
Upvotes: 1