SendKeys

This is a method for sending one or more keystrokes to the active window.
This should only be used as a last resort as it is not 100% secure and relies on the user not interupting the macro.
SendKeys allows you to send keystrokes to the currently active window and is often used to control applications that do not support any other form of communication.
An example of such an application is NotePad.


Simple Example

This example opens NotePad and sends a line of data before saving the file.

Public Sub OpenNotePad 
Dim vReturn As Variant
   vReturn = Shell("NotePad.exe", vbNormalFocus)
   AppActivate vReturn
   Application.SendKeys "Copy Data.xls C:\", True

'this sends an Enter
   Application.SendKeys "~", True

'this sends an (Alt + F + A) to perform a (File > Save As) and then enters the filename "BATCH" and presses Enter
   Application.SendKeys "%FABATCH~", True
End Sub

Multiple Keys

You can abbreviate sending the same key several times by appending a number inside the brackets
This has not been tested yet !!

Application.SendKeys "{Up 6}" 

This sends a Ctrl + F1

Application.SendKeys "^{F1}" 

Example of joined up

Application.SendKeys "{TAB}{TAB}" 

Potential Problems

When using SendKeys you often find that not all the keys sent reach the dialog box although sending all the keys at once does not make a difference.

Application.SendKeys "{Esc}" 

Enter simulate Tab

Make the Enter simulate the Tab key

Sub Form_KeyPress (keyAscii as integer) 
   If KeyAscii = vbKeyReturn Then
      SendKeys "{TAB}"
      KeyAscii = 0
   End If
End Sub

Reference Table

SHIFT"+"
CTRL"^"
ALT"%"
Backspace{Backspace}, {BS}, {BKSP}
Break{Break}
Caps Lock{CapsLock}
Delete{Delete}, {Del}
Down Arrow{Down}
End{End}
Enter{Enter}, ~
Escape{Esc}
Help{Help}
Home{Home}
Insert{Insert}, {Ins}
Left Arrow{Left}
Num Lock{NumLock}
Page Down{Pgdn}
Page Up{Pgup}
Print Screen{PrtSc}
Right Arrow{Right}
Scroll Lock{ScrollLock}
Spacebar{Space} or try " "
Tab{Tab}
Up Arrow{Up}
F1 - F16{F1} .. {F16}
TrueTrue
FalseFalse

© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrevNext