Detecting the Shift key

Here's another example: Suppose you've written a VBA macro that will be executed from button on a worksheet. Furthermore, suppose you want the macro to perform differently if the user presses the Shift key when the button is clicked. Normally, there is no way to detect whether the Shift key is pressed. But you can use the GetKeyState API function to find out. The GetKeyState function tells you whether a particular key is pressed. It takes a single argument, nVirtKey, which represents the code for the key that you are interested in.

CROSS- Chapter 11 has several additional examples of using Windows API functions.

REFERENCE

The following code demonstrates how to detect whether the Shift key is pressed when the Button_Click event handler procedure is executed. Notice that I define a constant for the 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 was not pressed.

Declare Function GetKeyState Lib "user32" _ (ByVal nVirtKey As Long) As Integer

Sub Button_Click()

Const VK_SHIFT As Integer = &H10 If GetKeyState(VK_SHIFT) < 0 Then MsgBox "Shift is pressed"

Else

MsgBox "Shift is not pressed" End If End Sub

CD- a workbook named ® key press. xlsm on the companion CD-ROM demonstrates how ROM to detect the following keys (as well as any combinations): Ctrl, Shift, and Alt.

0 0

Post a comment