How Hex number works in if statements

rajkavikumar

New Member
Joined
Oct 2, 2012
Messages
20
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?:confused:
 

Some videos you may like

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
Joined
Apr 25, 2006
Messages
19,834
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.

Anyway, for your case

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
Joined
Apr 25, 2006
Messages
19,834
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
Joined
Oct 2, 2012
Messages
20
Hey Thanks,
pgc01 I was not aware of that bit wise operations works in vba and that too using AND operator. :cool:
 

pgc01

MrExcel MVP
Joined
Apr 25, 2006
Messages
19,834
Hey Thanks,
pgc01 I was not aware of that bit wise operations works in vba and that too using AND operator. :cool:

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. :(
 

Watch MrExcel Video

Forum statistics

Threads
1,108,924
Messages
5,525,665
Members
409,658
Latest member
Yardcell

This Week's Hot Topics

Top