We want to know if the tab key is being pressed so we call a Windows API “GetAsyncKeyState” which keeps track of what is going on with our computer’s keyboard. Here is how to declare the API.

Public Declare Function GetAsyncKeyState Lib “user32.dll” (ByVal vKey As Long) As Integer

The API returns an Integer value which is really a 16-bit switch where each bit is a switch containing a 1 (ON) or 0 (OFF). A 16 bit binary switch looks something like this 1000100011110000. If our API sets the most significant bit to 1, the key is down. This is the only bit we are concerned with. We want to ignore all other bits.

To “Mask” out all of the other bits we use a Binary AND Operator. The Binary AND Operation compares each bit in two numbers. Where both bits equal 1 the Binary AND operation result is 1 (ON), otherwise, it is 0 (OFF). So if the API returns 1000100011110000 and we only want the left most switch we Binary AND it with 1000000000000000. But VBA doesn’t understand 1000000000000000 as a binary value. To tell VBA we want it to use a Binary AND Operation instead of a normal VBA AND, we have to tell VBA that we are not using normal numbers, rather one of the representations of Binary numbers. Hexadecimal is one such representation that VBA understands.

&H tells VBA the number that follows is a Hexadecimal number. &H8000 is the hexadecimal number 8000. And in hexadecimal 8 equals 1000 in Binary. So Hexadecimal 8000 is Binary 1000000000000000.

Coming full circle, ANDing &H8000 with GetAsyncKeyState(vbKeyTab) tells us if the tab key is currently held down.

Hope that helps. For more information Google “Wikipedia Hexadecimal”, “MSDN GetAsyncKeyState”, and “Binary AND Operation”

]]>GetAsyncKeyState(vbKeyTab) And &H8000

]]>