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

Getting a Reference to the Word Application Object

Once the proper references are set, you can declare an object variable of type Application:

	Dim Wrd As Word.Application
The References dialog box

Figure A-1. The References dialog box

which the Automation client will understand, because it can now check the server’s object library. Note that you need to qualify the object name, since other object models have an Application object as well.

Next, you can start the Word Automation server, create a Word Application object, and get a reference to that object. This is done in the following line:

	Set Wrd = New Word.Application

At this point, you have complete access to Word’s object model. It is important to note, however, that the previous line starts the Word Automation server, but does not start Word’s graphical user interface, so Word will be running invisibly. To make Word visible, you just set its Visible property to True:

	Wrd.Visible = True

You can now program as though you were within the Word VBA IDE. For instance, the following code creates a new document, adds some content to it, and saves the document:

	Dim doc as Word.Document
	Set doc = Wrd.Documents.Add
	doc.Content = "To be or not to be"
	doc.Save

Note that the Word server will not terminate by itself, even if the Wrd variable is destroyed. If you have made Word visible, then you can close it programmatically, as well as from the user interface in the usual ...

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