# How Hex number works in if statements

#### rajkavikumar

##### New Member
Hello Friends I am trying to understand how I can use Hex in my if statement rather how below mtioned code is working in if condition.
Code:
``````Sub test1()

Const T = &H1
Const P = &H2
Const D = &H20
R = P + D
If R And P Then
Debug.Print P
End If
If R And T Then
Debug.Print T
End If

End Sub``````

I also checked in immediate window that
R AND P returns 2
and
R and T returns zero

but I don't understand that how this get calculated? ### 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.

#### pgc01

##### MrExcel MVP
Hi

This is a very basic question that means that you did not study binary/hexadecimal numbers.
You should search the web for arithmetic/logical operation with binary numbers, or bitwise operations. I'm sure you'll find lots of tutorials.

T=P+D= 20H + 2H = 22H

To see the result of R and P, in Hexadecimal

22H
2H

since you are not used to it, convert the values to binary

00100010
00000010

Now it's easy to see that the only bit that is 1 in both numbers in the same place is the second one from the right, and so the result is

00000010

which converted to decimal is 2.

Hope this helps.

#### pgc01

##### MrExcel MVP
P. S.

Also notice that vba only has 1 And operator which may be kind of confusing since in the worksheet the And() function assumes it's a boolean operation while the vba And operator considers an expression like yours a bitwise operation.

#### rajkavikumar

##### New Member
Hey Thanks,
pgc01 I was not aware of that bit wise operations works in vba and that too using AND operator. #### pgc01

##### MrExcel MVP
Hey Thanks,
pgc01 I was not aware of that bit wise operations works in vba and that too using AND operator. Yes, as I said it's a bit confusing if you are not used to it. For ex. in C you have 2 different operators, 1 for the bitwise And (&) and another for the boolean And (&&) and so there is no confusion.

We are not that lucky with vba. Replies
3
Views
71
Replies
6
Views
74
Replies
3
Views
58
Replies
12
Views
179
Replies
2
Views
40