Reputation: 59
Im trying make a condition in excel VBA where there are two posible condition of variable x and y,
Say for example
Sub Test()
X = 6
Y = 11
If X < 3 Or X > 5 And Y < 10 Then
X = 10
Else
X = 11
End If
MsgBox X
End Sub
For the X term, when X<3 or X>5
seems work well however when i change the Y to any value greater than 10 say 11 then the result is 10 but supposed to be it should be 11. Can you please let me know if i missing something in my code so that when X<3 or X>5 and (y=11)>10
the result must be 11.
Regards, Kenneth
Upvotes: 1
Views: 1263
Reputation: 6190
This is an issue of operator precedence. In VB the order in Logical and Bitwise Operators is as follows:
The result is that and
is executed before or
in your condition, leading to the right side of the or
being the whole expression X > 5 And Y < 10
.
Your condition is executed like:
If X < 3 Or (X > 5 And Y < 10) Then
I believe what you actually want is the following (this should solve your issue):
If (X < 3 Or X > 5) And Y < 10 Then
Sources:
Upvotes: 4
Reputation: 96753
Consider:
Sub Test()
X = 6
Y = 11
If (X < 3 Or X > 5) And Y < 10 Then
X = 10
Else
X = 11
End If
MsgBox X
End Sub
Upvotes: 1