VBA - Sending keyboard commands

In previous posts (here and here) we've looked at keyboard listeners with a view to have our program listen for keyboard presses from the user and act upon them. In this post, we're going to have a look at the opposite, whereby our program sends a key command to the operating system for another program to respond to (i.e. simulated a key press).

VBA is the primary code for macros in Microsoft products (Excel, Access, etc.) and so to begin with, we're going to look at sending keyboard commands in VBA code. C#, C++ and Java equivalents may follow later.

Why send a key command

Sometimes we encounter issues which can only be solved with human input. This could be a confirmation window, such as the one shown below, or other form of user input.

A confirmation box requiring user input

A confirmation box requiring user input

If in our code, we interact with programs that are outside of our full control (e.g. we're creating add-ons or plugins for example), we might run into the problem of the outside program requiring user input that we cannot override. But for a fully automated system, we might not want to have the user give input for our code to execute successfully. So for this, we can simulate user input by sending a key command to the operating system, which will be interpreted by the current active window (which is typically the confirmation pop up, but it may be something else depending on what you're doing) and dealt with accordingly.

VBA Code to send a key command

In the image example above, you can get rid of the confirmation box entirely by using the save changes command (seen below). But other examples may require us to simulate a key press.

Simulating a key press in VBA is nice and easy, and is simply the command:

The 'application' refers to an object which is currently referencing an application. This could be a workbook in Excel for example. The 'keyPress' variable is the key you would like to send to your application (see the table below for a list of options), and the 'wait' variable is a true or false statement, which decides whether the operation waits for the key you send to be processed before returning control back to the macro code. If you choose false, you do run the danger of your key press being placed in a different application and not responding to what you actually intend to. The wait parameter is optional.

If your application is the code being worked on, then you can simply call the send keys method, as below.

Table of keys in VBA

A full table of the key presses you can send in VBA can be found here on the MSDN page. Note that key commands need to be in speech marks ("{ENTER}" not {ENTER}) in order to work.

Leave a Reply

Your email address will not be published. Required fields are marked *