Word, Excel, PowerPoint, Outlook, and Access all use the same VBA language. The only difference is their object models. For example, Excel has a Workbooks
object and Word has Documents
. Any one of these applications can access another application’s object model as long as the second application is installed.
To access Word’s object library, Excel must establish a link to it by using either early binding or late binding. With early binding, the reference to the application object is created when the program is compiled. With late binding, the reference is created when the program is run.
This chapter is an introduction to accessing Word from Excel.
Because this chapter does not review Word’s entire object model or the object models of other applications, refer to the VBA Object Browser in the appropriate application to learn about other object models.
Code written with early binding executes faster than code with late binding. A reference is made to Word’s object library before the code is written so that Word’s objects, properties, and methods are available in the Object Browser. Tips such as a list of members of an object also appear, as shown in Figure 18.1.
The disadvantage of early binding is that the referenced object library must exist on the system. For example, if you write a macro referencing Word 2010’s object library and someone with Word 2003 attempts to run the code, the program fails because the program cannot find the Word 2010 object library.
The object library is added through the VB Editor, as follows:
If the object library is not found, Word is not installed. If another version is found in the list such as 10.0, another version of Word is installed.
After the reference is set, Word variables can be declared with the correct Word variable type. However, if the object variable is declared As Object
, this forces the program to use late binding:
Excel searches through the selected libraries to find the reference for the object type. If the type is found in more than one library, the first reference is selected. You can influence which library is chosen by changing the priority of the reference in the listing.
This example creates a new instance of Word and opens an existing Word document from Excel. The declared variables, wdApp
and wdDoc
, are of Word object types. wdApp
is used to create a reference to the Word application in the same way the Application
object is used in Excel. New Word.Application
is used to create a new instance of Word.
If you are opening a document in a new instance of Word, Word is not visible. If the application needs to be shown, it must be unhidden (wdApp.Visible = True
).
When finished, it’s a good idea to set the object variables to Nothing
and release the memory being used by the application, as follows:
Set wdApp = Nothing
Set wdDoc = Nothing
If the referenced version of Word does not exist on the system, an error message appears, as shown in Figure 18.3. View the References list; the missing object is highlighted with the word MISSING (see Figure 18.4).
If a previous version of Word is available, you can try running the program with that version referenced. Many objects are the same between versions.
When using late binding, you are creating an object that refers to the Word application before linking to the Word library. Because you do not set up a reference beforehand, the only constraint on the Word version is that the objects, properties, and methods must exist. In the case where there are differences, the version can be verified and the correct object used accordingly.
The disadvantage of late binding is that because Excel does not know what is going on, it does not understand that you are referring to Word. This prevents the tips from appearing when referencing Word objects. In addition, built-in constants are not available. This means that when Excel is compiling, it cannot verify that the references to Word are correct. After the program is executed, the links to Word begin to build, and any coding errors are detected at that point.
The following example creates a new instance of Word, and then opens and makes visible an existing Word document:
An object variable (wdApp
) is declared and set to reference the application (CreateObject("Word.Application")
).
Other required variables are then declared (wdDoc
), and the application object is used to refer these variables to Word’s object model.
Declaring wdApp
and wdDoc
as objects forces the use of late binding. The program cannot create the required links to the Word object model until it executes the CreateObject
function.
The following sections describe how to create new objects and how to reference currently open objects.
New
KeywordIn the early binding example, the keyword New
was used to reference the Word application. The New
keyword can be used only with early binding; it does not work with late binding. CreateObject
or GetObject
would also work, but New
is best for this example. If an instance of the application is running and you want to use it, use the GetObject
function instead.
If your code to open Word runs smoothly, but you don’t see an instance of Word (and should because you code it to be Visible), open your Task Manager and look for the process WinWord.exe
. If it exists, from the Immediate window in Excel’s VB Editor, type the following (which uses early binding):
Word.Application.Visible = True
If multiple instances of WinWord.exe
are found, you need to make each instance visible and close the extra instance(s) of WinWord.exe
.
CreateObject
FunctionThe CreateObject
function was used in the late binding example. However, this function can also be used in early binding. CreateObject
has a class
parameter consisting of the name and type of the object to be created (Name.Type
). For example, the examples in this chapter have shown you (Word.Application
), in which Word is the Name
and Application is the Type
.
The CreateObject
function creates a new instance of the object. In this case, the Word application is created.
GetObject
FunctionThe GetObject
function can be used to reference an instance of Word that is already running. It creates an error if no instance can be found.
GetObject
’s two parameters are optional. The first parameter specifies the full path and filename to open, while the second parameter specifies the application program. The following example leaves off the application, allowing the default program, which is Word, to open the document:
This example opens a document in an existing instance of Word and ensures the Word application’s Visible
property is set to True
. Note that to make the document visible, you have to refer to the application object (wdDoc.Application.Visible
) because wdDoc
is referencing a document rather than the application.
Although the Word application’s Visible
property is set to True
, this code does not make the Word application the active application. In most cases, the Word application icon stays in the taskbar, and Excel remains the active application on the user’s screen.
The following example uses errors to learn whether Word is already open before pasting a chart at the end of a document. If Word is not open, it opens Word and creates a new document:
Using On Error Resume Next
forces the program to continue even if it runs into an error. In this case, an error occurs when we attempt to link wdApp
to an object that does not exist. wdApp
will have no value. The next line, If wdApp Is Nothing then
, takes advantage of this and opens an instance of Word, adding an empty document and making the application visible.
Note the use of empty quotes for the first parameter in GetObject("", "Word.Application")
. This is how to use the GetObject
function to open a new instance of Word. Use On Error Goto 0
to return to normal VBA handling behavior.
The previous example used constants that are specific to Word such as wdPasteOLEObject
and wdInLine
. When you are programming using early binding, Excel helps by showing these constants in the tip window.
With late binding, these tips will not appear. So what can you do? You might write your program using early binding, and then change it to late binding after you compile and test the program. The problem with this method is that the program will not compile because Excel does not recognize the Word constants.
The words wdPasteOLEObject
and wdInLine
are for your convenience as a programmer. Behind each of these text constants is the real value that VBA understands. The solution to this is to retrieve and use these real values with your late binding program.
One way to retrieve the value is to add a watch for the constants. Then, step through your code and check the value of the constant as it appears in the Watch window, as shown in Figure 18.5.
Another way to retrieve the value is to look up the constant in the Object Browser. However, you need the Word library set up as a reference to use this method. To set up the Word library, right-click in the constant and select Definition. The Object Browser opens to the constant that shows the value in the bottom window, as shown in Figure 18.6.
You can set up the Word reference library to be accessed from the Object Browser. However, you do not have to set up your code with early binding. In this way, the reference is at your fingertips, but your code is still late binding. Turning off the reference library is just a few clicks away.
Replacing the constants in the earlier code example with their real values would look like this:
However, what happens a month from now when you return to the code and you try to remember what those numbers mean? The solution is up to you. Some programmers add comments to the code referencing the Word constant. Other programmers create their own variables to hold the real value and use those variables in place of the constants, like this:
Word’s macro recorder can be used to get a preliminary understanding of the Word object model. However, much like Excel’s macro recorder, the results will be long-winded. Keep this in mind and use the recorder to lead you toward the objects, properties, and methods in Word.
The macro recorder is limited in what it allows you to record. The mouse cannot be used to move the cursor or select objects, but there are no limits in doing so with the keyboard.
The following example is what the Word macro recorder produces when adding a new, blank document.
Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
Making this more efficient in Word produces this:
Documents.Add
Template
, NewTemplate
, and DocumentType
are all optional properties that the recorder includes but are not required unless you need to change a default property or ensure that a property is what you require.
To use the same line of code in Excel, a link to the Word object library is required, as you learned earlier. After that link is established, an understanding of Word’s objects is all you need. The next section is a review of some of Word’s objects—enough to get you off the ground. For a more detailed listing, refer to the object model in Word’s VB Editor.
Document
ObjectWord’s Document
object is equivalent to Excel’s Workbook
object. It consists of characters, words, sentences, paragraphs, sections, and headers/footers. It is through the Document
object that methods and properties affecting the entire document such as printing, closing, searching, and reviewing, are accomplished.
To create a blank document in an existing instance of Word, use the Add
method. We already learned how to create a new document when Word is closed—refer to GetObject
and CreateObject
:
Sub NewDocument()
Dim wdApp As Word.Application
Set wdApp = GetObject(, "Word.Application")
wdApp.Documents.Add
Set wdApp = Nothing
End Sub
This example opens a new, blank document that uses the default template. To create a new document that uses a specific template, use this:
wdApp.Documents.Add Template:="Contemporary Memo.dotx"
This creates a new document that uses the Contemporary Memo template. Template can either be the name of a template from the default template location or the file path and name.
To open an existing document, use the Open
method. Several parameters are available including Read Only
and AddtoRecentFiles
. The following example opens an existing document as Read Only
, but prevents the file from being added to the Recent File List under the File menu:
After changes have been made to a document, most likely you will want to save it. To save a document with its existing name, use this:
wdApp.Documents.Save
If the Save
command is used with a new document without a name, the Save As dialog box appears. To save a document with a new name, you can use the SaveAs
method instead:
wdApp.ActiveDocument.SaveAs "C:Excel VBA 2007 by Jelen & _
SyrstadMemoTest.docx"
SaveAs
requires the use of members of the Document
object, such as ActiveDocument
.
Use the Close
method to close a specified document or all open documents. By default, a Save dialog appears for any documents with unsaved changes. The SaveChanges
argument can be used to change this. To close all open documents without saving changes, use this code:
wdApp.Documents.Close SaveChanges:=wdDoNotSaveChanges
To close a specific document, you can close the active document or you can specify a document name:
wdApp.ActiveDocument.Close
or
wdApp.Documents("Chapter 19 - Arrays.docx").Close
Use the PrintOut
method to print part or all of a document. To print a document with all the default print settings, use this:
wdApp.ActiveDocument.PrintOut
By default, the print range is the entire document, but this can be changed by setting the Range
and Pages
arguments of the PrintOut
method:
wdApp.ActiveDocument.PrintOut Range:=wdPrintRangeOfPages, Pages:="2"
Selection
ObjectThe Selection
object represents what is selected in the document, such as a word, sentence, or the insertion point. It also has a Type
property that returns the type that is selected such as wdSelectionIP
, wdSelectionColumn
, and wdSelectionShape
.
The HomeKey
and EndKey
methods are used to change the selection; they correspond to using the Home and End keys, respectively, on the keyboard. They have two parameters: Unit
and Extend
. Unit
is the range of movement to make, to either the beginning (Home
) or end (End
) of a line (wdLine
), document (wdStory
), column (wdColumn
), or row (wdRow
). Extend
is the type of movement: wdMove
moves the selection, wdExtend
extends the selection from the original insertion point to the new insertion point.
To move the cursor to the beginning of the document, use this code:
wdApp.Selection.HomeKey Unit:=wdStory, Extend:=wdMove
To select the document from the insertion point to the end of the document, use this code:
wdApp.Selection.EndKey Unit:=wdStory, Extend:=wdExtend
TypeText
The TypeText
method is used to insert text into a Word document. User settings, such as the Overtype
setting, can affect what will happen when text is inserted into the document:
Range
ObjectThe Range
object uses the following syntax:
Range(StartPosition, EndPosition)
The Range
object represents a contiguous area or areas in the document. It has a starting character position and an ending character position. The object can be the insertion point, a range of text, or the entire document including nonprinting characters such as spaces or paragraph marks.
The Range
object is similar to the Selection
object, but in some ways it is better. For example, the Range
object requires less code to accomplish the same tasks, and it has more capabilities. In addition, it saves time and memory because the Range
object does not require Word to move the cursor or highlight objects in the document to manipulate them.
To define a range, enter a starting and ending position, as shown in this code segment:
Figure 18.7 shows the results of running this code. The first 22 characters are selected including nonprinting characters such as paragraph returns.
The range was selected (wdRng.Select
) for easier viewing. It is not required that the range be selected to be manipulated. For example, to delete the range, do this:
wdRng.Delete
The first character position in a document is always zero, and the last is equivalent to the number of characters in the document.
The Range
object also selects paragraphs. The following example copies the third paragraph in the active document and pastes it in Excel. Depending on how the paste is done, the text can be pasted into a text box (see Figure 18.8) or into a cell (see Figure 18.9):
After a range is selected, formatting can be applied to it (see Figure 18.10). The following program loops through all the paragraphs of the active document and bolds the first word of each paragraph:
A quick way of changing the formatting of entire paragraphs is to change the style (see Figures 18.11 and 18.12). The following program finds the paragraph with the NO style and changes it to HA:
Bookmarks are members of the Document
, Selection
, and Range
objects. They can help make it easier to navigate around Word. Instead of having to choose words, sentences, or paragraphs, use bookmarks to manipulate sections of a document swiftly.
You are not limited to using only existing bookmarks. Instead, bookmarks can be created using code.
Bookmarks appear as gray I-bars in Word documents. In Word, click the Microsoft Office Button, and then select Options, Advanced, Show Document Contents to turn on bookmarks (see Figure 18.13).
After you have set up bookmarks in a document, you can use the bookmarks to move quickly to a range. The following code automatically inserts text after four bookmarks that were previously set up in the document. Figure 18.14 shows the results.
Bookmarks can also be used as markers for bringing in charts created in Excel. The following code pastes an Excel chart (see Figure 18.15) into the memo:
You have seen how to modify a document by inserting charts and text, modifying formatting, and deleting text. However, a document may contain other items such as controls that you can modify.
For the following example, a template was created consisting of text, bookmarks, and Form Field check boxes. (See the note following this paragraph for information on where the Form Fields are hiding in Word.) The bookmarks are placed after the Name and Date fields. Notice that the check boxes have all been renamed so they make more sense. For example, one bookmark was renamed chk401k rather than Checkbox5. Save the template.
The Word Form Fields are found on the Controls section of the Developer tab under Legacy Forms, as shown in Figure 18.16.
To rename a bookmark, right-click the check box, select Properties, and type a new name in the Bookmark field.
The questionnaire was set up in Excel, allowing the user to enter free text in B1 and B2, but setting up data validation in B3 and B5:B8, as shown in Figure 18.17.
The code goes into a standard module. The name and date go straight into the document. The check boxes use logic to verify whether the user selected Yes or No to confirm whether the corresponding check box should be checked. Figure 18.18 shows a sample document that has been completed.
Due to new security precautions, if the location is not trusted in the file’s parent application, the code might run into an error when opening a template containing macros or controls. For example, the previous code will run into an error when opening the template on a network. Therefore users need to either configure Word to trust the network location or save the files to a local drive before running the program. Another option is to use a document instead of a template and set the ReadOnly:=True
when opening the file.
In Chapter 19, “Arrays,” you learn how to use multidimensional arrays. Reading data into a multidimensional array, performing calculations on the array, and then writing the array back to a range can speed up your macros dramatically.