Access VBA Macro Programming

(Joao Candeias) #1

All the applications in the Microsoft Office Suite support OLE automation in that you can
load in a reference to a particular object model and then manipulate that application from
inside your code. See Chapter 17 on how to use other Microsoft applications from within
your code.
Other applications do not support this; a good example is the calculator application that is
supplied with Microsoft Windows. There is no access to an object model, but you can use
SendKeysto manipulate it.
SendKeyssends one or more keystrokes to the active window as if they had been entered
at the keyboard:


SendKeys keytext [,wait]


In this example,keytextis the string of keys to be sent to the active window;waitis a Boolean
value (True or False). Ifwaitis True, then the keys must be processed first before control is
returned to the procedure. Ifwaitis False, then control is returned to the procedure immediately
after the keystrokes are sent. Ifwaitis omitted, then False is assumed as the default.
The value ofwaitcan be extremely important when sending keys to another application.
If the application is running quickly, it may have moved on in execution by the time the key
statement comes across, so theSendKeysstatement gets ignored. You setwaitto True so
that the keystrokes are processed first, preventing the application from moving on ahead.
Generally, the keyboard keys themselves are used in theSendKeysstatement most of the
time. For example,


SendKeys "A123"


sends A123 to the current window.
Of course, this is assuming you have the relevant application running and that it is the
active window!
Two other commands will help with this. The first is theShellfunction. This allows your
code to launch another application and transfer control to it:


Shell (commandstring [,windowstyle])


Thecommandstringparameter is the command line to call the application. If you look at the
shortcuts on your desktop, you will see there is a text box called Target that holds the
pathname and filename of the application plus any necessary parameters. This is used as the
commandstring parameter.
Thewindowstyleparameter dictates how the application will be opened, whether it will
be opened as a normal window and icon or hidden.
Before you can send your keypresses to the application, you need to open it. The
following example opens the Windows Calculator:


x = Shell("calc.exe",1)


This opens the Windows Calculator application in a standard window with focus. Since it is
now the active window, you can useSendKeysto send keypresses to it.


Chapter 5: Strings, Functions, and Message Boxes 63

Free download pdf