Q:

Using a combination of IF, And in excel VBA

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

A:

This is an issue of operator precedence.  In VB the order in Logical and Bitwise Operators is as follows:

Negation (Not)
Conjunction (And, AndAlso)
Inclusive disjunction (Or, OrElse)
Exclusive disjunction (Xor)

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:

MSDN: Operator Precedence in Visual Basic

A:

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

