The VBA SendKeys method is used to send keystrokes to the active application:
The above code will mimic pressing the “s” key on the keyboard.
The SendKeys method takes two arguments:
- Keys – The key(s) you want to send to the application as text.
- Wait (Optional) – This value can either be True or False. If True, then Excel waits for the keys to be processed first before running the next line of code. If False, then Excel continues to run the procedure without waiting for the keys to be processed.
SendKeys is usually used when interacting with other applications because it’s a quick and easy way to accomplish tasks. For example, you might use SendKeys when automating Internet Explorer.
However, you should be extremely careful when using the SendKeys Method since it can have unexpected results. We recommend using SendKeys only as a last resort and/or when mistakes are tolerable (or easily detectable).
VBA SendKeys Examples
Each key in terms of letters is represented by their character, for example a is “a”.
If you would like to use keys in combination with Ctrl, Shift or Alt then you have to precede the key code with the following:
The following code uses the SendKeys Method to save the workbook:
Sub UsingSendKeys() Application.SendKeys ("^s") End Sub
As we mentioned before, you need to be extremely careful when using SendKeys. The following code specifies a waiting time of 10 seconds before the text is entered/sent to Notepad. By waiting 10 seconds, you allow Notepad a chance to open properly, reducing the chance of an error.
Note: This code uses the Application.Wait Method.
Sub UsingSendKeysWithWait() Call Shell("C:\Windows\system32\Notepad.Exe", vbNormalFocus) Application.Wait (Now() + TimeValue("00:00:10")) Call SendKeys("This is Some Text", True) End Sub
The result after 10 seconds of waiting time is:
SendKeys can be an extremely quick and easy way to accomplish tasks. However, the risks of errors are relatively high. Only use SendKeys when that risk is acceptable!