Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the VBA "And" operator evaluate the second argument when the first is false?

Function Foo(thiscell As Range) As Boolean   Foo = thiscell.hasFormula And (InStr(1, UCase(Split(thiscell.formula, Chr(40))(0)), "bar") > 0) End Function 

This function exists to test for the presence of a certain substring (bar, in this case) before the (.

The case I'm having trouble with is when the cell passed into the function is empty, the thisCell.hasFormula is false, but the statement after the and is still being evaluated. This gives me a subscript out of range error in runtime.

Does VBA actually continue evaluating the second argument to the And, even when the first was false?

like image 444
James Avatar asked Aug 10 '11 17:08

James


People also ask

What are the three main logical operators in VBA?

Logical operators compare Boolean expressions and return a Boolean result. The And , Or , AndAlso , OrElse , and Xor operators are binary because they take two operands, while the Not operator is unary because it takes a single operand.

Does VBA short-circuit?

VBA doesn't short-circuit VBA does not support short-circuiting - apparently because it only has bitwise And/Or/Not etc operations.

Does excel if short-circuit?

Well-known Member. Excel does use short-circuit evaluation of IF()s.


1 Answers

What you are looking for is called "short-circuit evaluation".

VBA doesn't have it.

You can see an approach that is probably adaptable to your situation here.

The approach that was chosen there involved substituting a Select Case for the If. There is also an example of using nested Ifs.

like image 111
DOK Avatar answered Sep 23 '22 23:09

DOK