Scripting Microsoft Word

Microsoft Word is a very powerful word processing application that is part of the Microsoft Office suite. It has become probably the single most widely used application of its type. But you already know this. What you may not know is that Microsoft Word was created with script automation in mind.

The developers at Microsoft have included an OLE automation object for Word that allows you to control it both internally with macros and externally with WSH.  Today we’re going to explore this automation object and some of its uses.

So some of you may be thinking, “Why should I even care?  I’m not going to automate typing a paper.”  And you’re probably right.  It would be far too tedious to automate typing a paper, but there are other possibilities.

Word is excellent for creating reports.  You could create an automation that pulls information from a database, creates and formats a report, and then sends it off to a network printer.  Wouldn’t it be nice to have overnight sales orders waiting on the printer when you arrive at the office each morning?

You already know that Microsoft Word can work very closely with an Access database for creating form letters.  Why not automate the creation of personalized form letters and envelopes for your entire mailing list?  And the possibilities go on.

Getting started is pretty simple.  You first need to create an instance of the Word automation object.  This will differ slightly depending upon what language you use, but here’s what it looks like in VBScript.

Set objWord = CreateObject("Word.Application")

“Word.Application” is a version independent ProgId that will connect to the OLE object with the most recent version number.  So don’t worry if you have or have had multiple versions of Word installed; you’ll always be working with the most recent.

This basically launches the Microsoft Word application in memory.  Let’s look at a couple of things we can do to control how the application opens.

objWord.DisplayAlerts = False

objWord.Visible = False

DisplayAlerts is a Boolean property that, when set to False, suppresses file type warnings when opening older version files.  To avoid needing any outside user input, it’s a good idea to make sure that unnecessary message boxes are always suppressed.

Visible is a hidden property that accepts a Boolean value that determines whether or not the Word application is displayed on screen or opened in the background.  Setting this value to True will make the application visible.  This is sometimes useful during script creation and testing.

{mospagebreak title=Creating and Opening Documents}

At this point, the Word application is running but we don’t have any open documents to work with.  I’ll show you how to create a new document, open an existing one, and switch back and forth between multiple open documents.  Let’s begin by creating a new document.

Set objNewDoc = objWord.Documents.Add

Here I’ve created a new document based on the Normal template.  The most effective way to create a new document is by using the Add method of the Documents collection.  The Documents collection is a collection of Document objects that represents all open documents.

Documents.Add(Template, NewTemplate, NewDocumentType, Visible)

You may provide optional attributes to the Add method.  Template is a string that indicates a path to a document template to use.  If omitted, the default Normal template is used.  NewTemplate is a Boolean value that indicates whether or not to open the new document as a template.  NewDocumentType accepts any one of the wdNewDocumentType constants listed in the table below.  If omitted, the default wdNewBlankDocument (0) is used.  Visible is a Boolean value that indicates whether or not the document should be opened in a visible window.  This defaults to True but will be overridden if the Word object itself has visibility set to False.

wdNewDocumentType Constants

wdNewBlankDocument = 0

wdNewWebPage = 1

wdNewEmailMessage = 2

wdNewFrameset = 3

wdNewXMLDocument = 4

The following example uses the Documents.Add method to open a new document using the Professional Memo template.

strTemplate = "C:Program FilesMicrosoft Office" _

   & "TemplatesMemosProfessional Memo.dot"

Set objDoc = objWord.Documents.Add(strTemplate)

The Documents collection object also provides an Open method that you can use to open an existing document.  The Open method provides very extensive syntax; however, it only requires a single attribute that represents the path to the file to be opened.  Each of the attributes may also be set using equivalent properties provided by the Documents object.  I’ll show you both ways and you’ll understand what I mean.

For brevity’s sake, I won’t be discussing all of the available attributes since most will go unused.  For more information on the Open method and its available attributes, consult the MSDN documentation here.

Documents.Open(FileName, ConfirmConversions, ReadOnly, AddToRecentFiles, PasswordDocument, PasswordTemplate, Revert, WritePasswordDocument, WritePasswordTemplate, Format, Encoding, Visible, OpenConflictDocument, OpenAndRepair, DocumentDirection, NoEncodingDialog)

For most purposes, we’ll only be concerned with the first and third attributes.  FileName is a string that represents the path to the document file.  This may be a local path or any fully qualified UNC path to a network file.  You can even use URLs.

If you are using Jscript, don’t forget to escape any and all forward slashes in your paths!

The third attribute is optional and accepts a Boolean value indicating whether or not to open the document as Read-Only.  This can be used as an added safety precaution.  For example, you may want to print out a document with some changes without affecting the original document.

Set objDoc = objWord.Documents.Open("MyDoc.doc",, True)

The previous example opens the document MyDoc as Read-Only.  Any changes made to the document will not be saved to the original.  We’ll see later how to save a document in case you would like to save the changes to a new document.

Now that you know how to open new and existing documents, you need to know how to switch back and forth between them.  The Document object provides an Activate method that allows you to specify which document has focus.  The Word Application object also provides a read-only ActiveDocument property that returns a reference to the currently active document.

Be aware that the ActiveDocument property will result in an error if there are no documents open.  A simple If statement can be used to prevent this.

In the following example, we’re going to switch between our two open documents.  The newly opened document should have focus already.  We’ll switch back to the new document we created.  I’ll use a message box to indicate that the switch was made.  Notice how I use a simple If statement to check for open documents in order to avoid any errors.  I’m assuming that if there is at least one document open, then both required documents are open.

If objWord.Documents.Count >= 1 Then

   objNewDoc.Activate

   MsgBox "The " & objNewDoc.Name & " document has been activated. "

Else

   MsgBox "There are no documents open."

End If

Here, we’re using the Activate method to focus on the objNewDoc object.  We’re checking the Count property of the Documents collection to ensure that it contains references to open documents.

The Word Application object also provides an Activate method that can be used to switch between multiple running instances of the Word application!

{mospagebreak title=Editing and Formatting Documents}

We’re now going to explore a few ways to edit documents.  Please note that this section is only a very brief introduction.  You will most likely need to do some experimentation with your own documents since editing is highly dependent upon the styles and formatting that exist within the document.

To begin, we’re going to assume that we’re working with our newly created blank document.  We’ll first want to add a couple of paragraphs.

Set objSelection = objWord.Selection

We begin by selecting the contents of your document.  In our new document, we’re simply creating an empty selection but we’ll need that selection reference to type our paragraphs.

objSelection.Font.Name = "Arial"

objSelection.Font.Size = "10"

objSelection.TypeText "=rand(1,5)"

objSelection.TypeParagraph()

 

objSelection.Font.Size = "12"

objSelection.TypeText "=rand(1,5)"

objSelection.TypeParagraph()

Adding text is quite simple.  I’m using a few selection properties to control some basic formatting such as font face and size, and then typing the text to be inserted using the TypeText method.  The TypeParagraph method is used to insert paragraph breaks between my text samples.

The TypeText method accepts a single attribute that should be the literal text to be included.  Since I’m lazy (and I didn’t want to clog up my code with a bunch of lengthy paragraphs) I’ve used a little known Word function to insert some random sample text for me.

Depending on your Word version and regional settings, your document should now contain two paragraphs that look similar to the following:

On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document. You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. When you create pictures, charts, or diagrams, they also coordinate with your current document look. You can easily change the formatting of selected text in the document text by choosing a look for the selected text from the Quick Styles gallery on the Home tab. You can also format text directly by using the other controls on the Home tab.

 

On the Insert tab, the galleries include items that are designed to coordinate with the overall look of your document. You can use these galleries to insert tables, headers, footers, lists, cover pages, and other document building blocks. When you create pictures, charts, or diagrams, they also coordinate with your current document look. You can easily change the formatting of selected text in the document text by choosing a look for the selected text from the Quick Styles gallery on the Home tab. You can also format text directly by using the other controls on the Home tab.

If you’re using a Word version older than Word 2007 you will probably see something more like this:

The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.

 

The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog. The quick brown fox jumps over the lazy dog.

In any case, we have a few sample paragraphs to work with now.  Let’s take a look at how we can append paragraphs to a Word document and how to insert them between other paragraphs.  To do both of these, we’ll need to change our selection.

Const wdStory = 6

Const wdMove = 0

 

Set objSelection = objWord.Selection

objSelection.EndKey wdStory, wdMove

 

objSelection.Font.Size = "14"

objSelection.Font.Bold = True

objSelection.TypeText "=lorem(1,5)"

objSelection.TypeParagraph()

The code sample above will append a paragraph to the end of our document.  Notice how I’ve reset my selection before changing anything.  This ensures that the entire document’s contents are selected.

Next I use the EndKey method.  This method moves or extends a selection from the end of the specified unit.  I’m telling Word to move my selection to the end of the entire story (the full document contents).  I now have an empty selection immediately following the document’s contents.  Here, I just write a new paragraph as before.

Set objSelection = objWord.Selection

objSelection.HomeKey wdStory, wdMove

 

objSelection.Font.Size = "14"

objSelection.Font.Bold = True

objSelection.TypeText "=lorem(1,5)"

objSelection.TypeParagraph()

I use the same procedure to insert a paragraph at the beginning of my document as well.  The only difference is that I’m using the HomeKey method instead of the EndKey method.  This moves my selection to the beginning instead of the end.

Const wdParagraph = 4

 

Set objSelection = objWord.Selection.Paragraphs(2)

objSelection.EndKey wdParagraph, wdMove

 

objSelection.Font.Size = "14"

objSelection.Font.Bold = True

objSelection.TypeText "=lorem(1,5)"

objSelection.TypeParagraph()

To insert paragraphs we use the same two procedures.  We can iterate through the paragraphs collection to select single paragraphs within the document.  Once we have a single paragraph selected, we can simply type a new paragraph either before or after it.  The code sample above inserts a paragraph between our two original paragraphs.

I’ve done this by selecting the second paragraph in the document and then inserting a paragraph after it.  Notice that I’m now using the wdParagraph unit size with the EndKey method because I want to move to the end of the current paragraph rather than the end of the current document.  You can view all of the available unit size constants in the MSDN documentation here.

{mospagebreak title=Closing, Saving, and Exiting}

Now that you’ve learned how to open and edit documents using the Word automation object, we’ll look at how to close them.  You can optionally save your document as well.  Just as within the Word application itself, you can save an opened document or save as a new document.

Const wdDoNotSaveChanges = 0

Const wdSaveChanges = -1

Const wdPromptToSaveChanges = -2

 

objDoc.Close wdSaveChanges

The Document object provides a Close method for closing open documents.  It does not require any parameters but has a few optional ones to determine whether a file should be saved and what format to save it with.  For more information see the MSDN documentation here.  In this example, we are saving changes before closing the document.

objDoc.Save True

You can save documents without closing by using the Save method.  I’ve included an optional parameter that suppresses the save changes dialog box.

You can save all open documents simultaneously by using the Save method provided by the Documents collection object.

Finally, you can save a document as a new document by using the SaveAs method.  This is essentially the same as using the Save As… command from the File menu and has optional parameters that include most of the options available with the Save As… dialog.  For our purposes, we’ll just look at how to save a document with a new name.  For more information, consult the MSDN documentation here.

objDoc.SaveAs "mynewdoc.doc"

Any time that you use the Word automation object, you want to be sure to close the application or it will continue to run in memory even after your script exits.  The Word object provides the Quit method for this purpose.  You may also supply optional parameters, including one of the wdSaveOptions constants you saw with the Close method above.

objWord.Quit wdDoNotSaveChanges

The above line is very common when automating Word from a VBScript.  This quits then closes all open documents and quits the Word application without prompting you to save changes.

You now have a good framework to begin exploring different ways of automating the Microsoft Word application using its OLE automation object.  You may find this a little frustrating in the beginning, but the MSDN documentation is very thorough and there are several sample scripts available if you do a bit of Googling.  I’ll be featuring some more advanced techniques using the Word automation object in an upcoming article.  Until next time, keep coding!

3 thoughts on “Scripting Microsoft Word

  1. In this article, we look at scripting the Microsoft’s Word Automation Object for controlling and automating Microsoft Word.

[gp-comments width="770" linklove="off" ]