O'Reilly logo

Writing Word Macros, Second Edition by Steven Roman PhD

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

An Alternative Approach

The previous approach for programming Word from within another application is the preferred approach, since it is the most efficient. However, there is an alternative approach that you may encounter, so I will discuss it briefly. As before, I assume that a reference has been set to the Word object library.

The CreateObject Function

The CreateObject function can start an Automation server, create an object, and assign it to an object variable. Thus, you can write:

	Dim Wrd as Word.Application
	Set Wrd = CreateObject("Word.Application")

This approach will execute more slowly than the previous approach using the New keyword, but it is perfectly valid.

As before, you must remember to close Word using the Quit method (or through normal means if Word is visible).

The GetObject Function

If Word is already running, the CreateObject function will start a second copy of the Word server. To use the currently running version, use the GetObject function to set a reference to the Application object of a running copy of Word. This is done as follows:

	Set Wrd = GetObject(, "Word.Application")

(The first parameter of GetObject is not used here.)

One of the problems with using GetObject is that it will produce an error if Word is not running, so it is somewhat unpredictable, for you cannot be sure that the user has not closed Word. Thus, you need some code that will start Word if it is not running or use the existing copy of Word if it is running.

The trick to this is to know that if ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required