Microsoft Office Tutorials and References
In Depth Information
Using the Windows API
Shift key (using a hexadecimal value) and then use this constant as the argument for
GetKeyState . If GetKeyState returns a value less than zero, it means that the Shift key was
pressed; otherwise, the Shift key wasn’t pressed. This code isn’t compatible with Excel 2007.
Declare PtrSafe Function GetKeyState Lib “user32” _
(ByVal nVirtKey As Long) As Integer
Const VK_SHIFT As Integer = &H10
If GetKeyState(VK_SHIFT) < 0 Then
MsgBox “Shift is pressed”
MsgBox “Shift is not pressed”
A workbook named key press.xlsm on the companion CD-ROM demonstrates how
to detect the following keys (as well as any combinations): Ctrl, Shift, and Alt. The
declarations in this file aren’t compatibile with 64-bit Excel. The API function declaration in
this workbook is compatible with Excel 2007 and later.
Learning more about API functions
Working with the Windows API functions can be tricky. Many programming reference books list
the declarations for common API calls and often provide examples. Usually, you can simply copy
the declarations and use the functions without really understanding the details. In reality (at least
the reality that I’ve seen), most Excel programmers take a cookbook approach to API functions.
The Internet has dozens of examples that you can copy and paste and that work quite reliably.
Chapter 11 has several additional examples of using Windows API functions.
The companion CD-ROM includes a file named win32api.txt , which is a text file that
contains Windows API declarations and constants. You can open this file with a text
editor and copy the appropriate declarations to a VBA module.