How to use Automation with Word 2002

For a Microsoft Word 2000 version of this article, see
237337 .
For a Microsoft Word 97 version of this article, see
184974 .
For a Microsoft Word 98 version of this article, see
184983 .


This article describes and demonstrates how to automate Microsoft Word 2002 from another program using Visual Basic or Visual Basic for Applications.

More Information

Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.

What is Automation?

Automation (also called OLE Automation) in Visual Basic is the process of controlling one program from another program or external development tool. You can automate any program that contains a Visual Basic object model. An object model is a hierarchical collection of the program's objects that are available or exposed to Visual Basic.

For example, the object model for Microsoft Excel contains objects such as worksheets, charts, cells, and ranges of cells. The Word object model contains objects such as documents, paragraphs, bookmarks, and ranges of text.

Each of these objects has a unique set of methods and properties required to manipulate them in Visual Basic. For example, you can save, print, or open a document, or you can change the font for a range of text.

Getting Started

The code samples in this article demonstrate how to control Microsoft Word 2002 from Microsoft Access 2002, Microsoft Excel 2002, Microsoft PowerPoint 2002, Microsoft Visual Basic 6.0, or any program that includes a Visual Basic development tool.

There are four main steps to automating Word 2002:
  1. Add a reference to the Microsoft Word 10.0 Object Library.
  2. Declare a variable as a Word object type (typically Word.Application or Word.Document).
  3. Assign the GetObject or CreateObject method to the object variable you declared in step 2.
  4. Use the Word object's properties, methods, and child objects to automate Word.

Step 1: Add a Reference to the Word Object Library

To add a reference to the Microsoft Word 10.0 Object Library by using Access 2002, PowerPoint 2002, or Excel 2002, follow these steps:
  1. In Access, PowerPoint, or Excel, point to Macros on the Tools menu, and then click Visual Basic Editor.
  2. On the Tools menu, click References.

    NOTE: To add the reference using Microsoft Visual Basic 6.0, click References on the Project menu.
  3. In the list of Available References, click to select the Microsoft Word 10.0 Object Library check box.
Adding the Microsoft Word 10.0 Object Library reference allows your program to access Microsoft Word Online Help and the Word object model. Because the references are saved in each project, you will have to add the Word object library reference for each Visual Basic or Visual Basic for Applications project that you want to automate Word.

Step 2: Declare the Object Variable

To declare a Word object variable, dimension a variable as a specific Word object type, such as Word.Application, Word.Document, or Word.Paragraph.

Explicitly declaring the object type is called early binding because the controller application connects or binds the object to the Word application at compile-time rather than at run-time. This gives you access to Word auto lists and context sensitive Help, and allows the code to run more efficiently.

For additional information about object binding, click the article number below to view the article in the Microsoft Knowledge Base:
138138 INFO: Late, ID, Early Binding Types Possible in VB for Apps
The following sample Visual Basic argument declares the variable oWord as an object of type Word.Application:

   Dim oWord as Word.Application

Step 3: Set the Variable

There are two Visual Basic methods you can use to activate Word: CreateObject and GetObject. The primary difference is that the CreateObject method creates a new instance of Word, and the GetObject method uses an already running instance of Word. You can also use GetObject to set your object variable to a specific Word document.

The following sample argument sets the oWord variable to the Word application using the CreateObject function:
   Dim oWord as Word.Application

Set oWord = CreateObject("Word.Application")
The following sample argument sets the oDoc variable to a specific Word document:
   Dim oDoc As Word.Document

Set oDoc = GetObject("c:\my documents\doc1.doc")
In some cases, you might want to use an existing Word instance if Word is already running, but create a new instance if Word is not running. To do this, create an error handler that uses the CreateObject method in the event that the GetObject method fails, as shown in this sample code:
   On Error Resume Next

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

If Err.Number <> 0 Then
Set oWord = CreateObject("Word.Application")
End If
NOTE: If you intend for users to see the Word window when your macro runs, set the Word object's Visible property to True, as shown in the following argument (where oWord is the name of your Word application object):
   oWord.Visible = True

Step 4: Use the Word Objects, Methods, and Properties

After you complete steps 1 through 3, you can use the Word object variable to automate Word.

The following sample macro uses automation to start Word, create a new document, add some text, and save the document.
Sub AutoWord()

' Declare the variable.
Dim oWord As Word.Application

' Set the variable (runs new instance of Word).
Set oWord = CreateObject("Word.Application")

' Add a new document.

' Add some text.
oWord.Selection.TypeText "This is some text."

' Save the document.
oWord.ActiveDocument.SaveAs Filename:="mydoc.doc"

' Quit Word.

' Clear the variable from memory.
Set oWord = Nothing

End Sub
When developing automation, it is good practice always to specify the parent object for any object, property, or method you invoke. That is because certain objects (such as a Selection object or a Range object) are not unique to one application. For example, you might intend to select a range of text in a Word document when automating Word from Excel. However, if you do not specify that this range applies to the Word document object, you might return an error or accidentally select a range of cells in the Excel workbook.

When automating Word, the parent object usually is the Word application or a Word document. You can specify this either by preceding each argument with the name of the Word object and a period (as in the AutoWord macro shown earlier in this article), or by placing the code inside a With...End With statement (as shown in the next macro). If you choose this latter method, precede each object, method, or property that applies to the Word object with a period, which connects it to the Word object invoked by the With...End With statement.

Be especially careful about specifying the parent object when defining variables and method parameters. The parent object is easy to forget in these cases because variable definitions and method parameters will not be at the beginning of the code line.

For example, the following sample macro defines the variable oPara3 as the third paragraph in a Word document. Note the period before
Paragraphs(3) connecting it to the oDoc object:
Sub AutoWord

Dim oDoc As Word.Document
Dim oPara3 As Word.Paragraph

Set oDoc = GetObject("c:\my documents\doc1.doc")
With oDoc
.Parent.Visible = True
Set oPara3 = .Paragraphs(3)
End With

End Sub
The following sample types the user name into a new document. For the Text parameter, note the repetition of oWord before its child object, ActiveDocument:
Sub AutoWord()

Dim oWord As Word.Application

Set oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Selection.TypeText Text:=oWord.ActiveDocument. _

End Sub


Microsoft Office Developer Web Site

For additional information about automating Word, please see the following Microsoft Web site:


The following peer-to-peer newsgroup is available to help you interact with other users of Visual Basic for Applications:

Knowledge Base

For more information about how to use the sample code in this article, click the article number below to view the article in the Microsoft Knowledge Base:
290140 OFFXP: How to Run Sample Code from Knowledge Base Articles
For additional information about getting help with Visual Basic for Applications, click the article number below to view the article in the Microsoft Knowledge Base:
305326 OFFXP: Programming Resources for Visual Basic for Applications

Office Assistant

For more information about about using CreateObject, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type createobject function in the Office Assistant or the Answer Wizard, and then click Search to view the topic.

For more information about about using GetObject, in the Visual Basic Editor, click Microsoft Visual Basic Help on the Help menu, type getobject function in the Office Assistant or the Answer Wizard, and then click Search to view the topic.

Id. de artículo: 307216 - Última revisión: 2 ago. 2012 - Revisión: 1