Sending Keystrokes

When you're operating in the Microsoft Windows operating system, the only way to communicate with applications that don't support OLE, OLE Automation, or DDE is by sending keystrokes using the SendKeys method.

Note

You can send keystrokes only to a Windows-based application that's running. MS-DOS–based applications and Macintosh applications don't accept keystrokes.

The SendKeys method is processed when your system is idle or when the DoEvents method is called. If the wait argument of the SendKeys method is True, Microsoft Excel waits for the keys to be processed before it returns control to the procedure; if the wait argument is False, the procedure continues to run without waiting for the keys to be processed. The following example sends keystrokes to the Calculator that add the numbers from 1 to 10 and then close the Calculator.


Sub DemoSendKeys()
    returnvalue = Shell("calc.exe", 1)
    AppActivate returnvalue
    For i = 1 To 10
        SendKeys i & "{+}", True
        Next i
        SendKeys "=", True
        SendKeys "%{F4}", True
End Sub

Note

Keystrokes are sent to the active application. If the active application isn't the one you want to send keystrokes to, you need to activate it using the AppActivate statement. If the application you want to send keystrokes to isn't already running, start it using the Shell function. If you don't specifically activate another application, your DDE procedure will send keystrokes to itself.

To specify characters that aren't displayed when you press the key (such as ENTER or TAB), enclose the key code in braces ({}), and enclose the braces in double straight quotation marks. To specify a key to be used in combination with SHIFT, CTRL, or ALT, precede the braces with "+", "^", or "%", respectively. The following example sends the key combination ALT+F4.


SendKeys "%{F4}", True

For a complete list of key codes, see "SendKeys method" in Help.

Note

You cannot send keystrokes that generate interrupts instead of character codes; for example, you cannot send ALT+CTRL+DEL or print scrEEn.