why does the And function not work here?

kalim

Board Regular
Joined
Nov 17, 2010
Messages
87
Hi excel users.

Can someone explain to me why the code below evaluates to true when it should evaluate to false. (Yes I know the second or statement is the same - Changing it does fix the problem -I fixed it in my real code), but shouldn't it still evaluate to false regardless, as the first condition is false?
'Range("e9") = 1'. Yes E9 is blank.

Code:
Sub test()
 
If Range("e9") = 1 And Range("f9") = 1 Or Range("f9") = 1 Then
   Range("e10") = "yes"
Else: Range("e10") = "no"

End If
End Sub

Thanks.
 

Excel Facts

Select a hidden cell
Somehide hide payroll data in column G? Press F5. Type G1. Enter. Look in formula bar while you arrow down through G.
Never mind I worked it out. I forgot to add brackets. Should be...

Code:
Sub test()
 
If Range("e9") = 1 And (Range("f9") = 1 Or Range("f9")) = 1 Then
   Range("e10") = "yes"
Else: Range("e10") = "no"

End If
End Sub
 
Upvote 0
First off, And is an operator in the VB world, not a function. I think the problem you seeing has to do with operator precedence and the fact that VB does not "short-circuit" its expression evaluation (meaning it evaluates the entire expression before returning its answer). The And operator has a higher precedence than Or operator, so in this arrangement... "A And B or C", I believe the "A and B" get evaluated to either True or False and then that is Or'ed with C to produce a final evaluated Boolean value. If I am right, then that would mean if C is True, then the whole expression evaluates to True no matter what "A And B" evaluates to. Usually it is a good idea to use parentheses to group the expressions in the order you want them evaluated in.
 
Upvote 0

Forum statistics

Threads
1,224,525
Messages
6,179,317
Members
452,905
Latest member
deadwings

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top