Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to use SendKeys to imitate the keyboard

Office / VBA General

How to use SendKeys to imitate the keyboard

by  BrainB  Posted    (Edited  )

If you perform the process using the keyboard you will note that things do not happen instantly on screen - especially the initial opening of a dialog box where the action takes place. The main problem with SendKeys is that the code usually runs faster than Windows can carry out the required activity - this is especially so if manipulating an external (not the one with the code) application or opening a dialog box or menu. We therefore need to slow the action down by using Wait statements. SendKeys also has its own "Wait" argument True or False which needs to be used correctly. One example of using it set to True is when manipulating external applications that require extra time to carry out actions. This is not always sufficient, so extra code is required.

A big key to success in this area is to break down the process into small steps. It does need a bit of trial and error to get it right. Experience shows that operators are prepared to wait a bit longer if it works. Sometimes the speed of external applications varies so much that the job is impossible using SendKeys, when using API calls with KeyUp and KeyDown work better. This area is never an exact science. See VBA Help 'SendKeys' and 'Shell' for more information.

This is some sample code to demonstrate the principle :-
'------------------------------------------
Sub SET_A3()
'- change Printer setting to A3 size
'- nb. assumes current setting is A4
Dim AltKey As String
Dim CtrlKey As String
Dim ShiftKey As String
Dim TabKey As String
Dim EnterKey As String
'--------------------------
AltKey = "%"
CtrlKey = "^"
ShiftKey = "+"
TabKey = "{TAB}"
EnterKey = "~"
'--------------------------
'- open print dialog
SendKeys AltKey & "(FP)", False
'- delay 1 second
Application.Wait Now + TimeValue("00:00:01")
'- open printer properties
SendKeys AltKey & "(R)", False
'- tab to paper size
SendKeys TabKey, False
SendKeys TabKey, False
'- change A4 to A3
SendKeys "{UP}", False
'- Enter twice
SendKeys EnterKey, False
SendKeys EnterKey, False
End Sub
'----------------------------------------------


Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top