Can I use AND in macro IF statement?

Can I use AND, OR in macro if statements like we can in other languages -

for example in python we can use && operator like If(condA =true && condB = true) --code here

We can use it in the spreadsheet but can we use it the Macro Basic? if yes, please give one example too, thank you. Other Than nested IF statements

edit retag close merge delete

Sort by » oldest newest most voted

Hello,

Here is a simple example. Note you must be careful on grouping conditions:

Sub ifTest
a = 2
b = 6
if (a = 2 or 3) and (b > 5) then
MsgBox "Yes"
Else
MsgBox "No"
End if
End sub

There are many reference manuals available on-line. Here is a good one -> OpenOfice Macros Explained

Also, that is not a Python statement you present. See -> Python If ... Else for example.

more

a = 2 or 3 might give not what you expect ;-)

( 2020-02-13 08:04:02 +0200 )edit

Thanks, It worked

( 2020-02-13 13:05:05 +0200 )edit

You are absolutely correct :)

Pretty bad mistake on my part :(

( 2020-02-13 17:42:54 +0200 )edit

... and below I also made a mistake, not taking operation precedence rules of Basic myself :-)

( 2020-02-13 19:49:00 +0200 )edit

In Basic NOT, AND, OR, XOR are operators named with respect to their meaning if used with Boolean operands. They can also be used (for masking purposes e.g.) with integer (Long) operands. They are applied bit-by-bit in this case. Thus you get 5 OR -7 = -3 e.g.

As known from ordinary algbra the operators are "prioritized" in a specific way. In case of the logical operators the NOT binds closest to the single operand at its right side. AND has highest príority among the two-sided operands like the * in arithmetic. OR has less binding force like the + , and concerning the XOR, I'm not sure.

You see, I have to admit that doubt may occur, this the more if integer expressions come into account. Therefore my advice: If you not are completely sure about the way priorities rule your expressions, disambiguate everything with the help of parentheses.

more

(a = 2) or (a = 3)

Sub ifTest
a = 4
b = 6
if (a = 2) or (a = 3) and (b > 5) then
MsgBox "Yes"
Else
MsgBox "No"
End if
End sub
more

(a = 2) or (a = 3) and (b > 5) might give not what you expect ;-)

( 2020-02-13 12:37:09 +0200 )edit

For the above function it works.

( 2020-02-13 13:44:20 +0200 )edit

Agreed, in Basic AND and OR have the same precedence, and are evaluated left-to-right.

( 2020-02-13 14:41:26 +0200 )edit