VBA: Simulate keyboard typing with sendKeys statement
sendKeys is a VBA statement to simulate keyboard typing into the active window.
The first (mandatory) parameter is a string that specifies the keys to be sent. The second (optional) parameter is a boolean that specifies if sendKeys returns to the caller before all key strokes were processed (true: wait until they're processed, false: return immediately).
Except the special characters +, ^, %, ~, ( and ), each key stroke is represented by its character. The special characters have the following meaning: +: shift ^: ctrl %: alt
Parentheses apply a special character's meaning to a series of characters. Thus +(abc) indicates that first shift is pressed, then an a followed by a b and a c and only then the shift is released.
The curly braces are used to type other special keys of the keyboard:
{backspace} or {bs} or {bksp}: backspace
{break}: break
{capslock}: caps lock
{del} or {delete}: delete
{down}: down arrow (etc.)
{f1}: F1 function key (etc.)
It's possible to simulate the repeated pressing of a key: {UP 42} »presses« the up arrow key 42 times.
In order to »press« curly braces, they need to be enclosed in curly braces themselvs: {{} or {}}.
Writing into notepad and saving the text file
The following example starts notepad, types some text into it, and uses ctrl-s to open the safe as dialog where a file name is sent.
option explicit
#if VBA7 then
public declare ptrSafe sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr) ' 64-Bit versions of Excel
#else
public declare sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long ) ' 32-Bit versions of Excel
#end if
sub main()
const fileName = "c:\temp\sendKeys.txt"
dim taskID as integer
taskID = shell("notepad.exe", vbNormalFocus)
'
' Delete final file if it was already written
'
if dir(fileName) <> "" then kill fileName
sendKeys "Hello World!" , true
sendKeys "~The tilde means a new line.", true
'
' Bring up the file save as dialog using
' the ctrl-s key combination
'
sendKeys "^s", true
'
' wait 0.2 seconds, hopefully, the safe as dialog will be initialized by then.
'
sleep 200 '
'
' Apparently, this space (or any other character?) is needed to
' somehow activate the safe as dialog.
'
sendKeys " ", true
'
' Send the filename
'
sendKeys fileName, true
'
' Send enter to close the dialog and
' save the file.
'
sendKeys "~", true
end sub