The Word Object Model


There are several handy built-in tools you can use when working with the Word object model in Access databases. They are described in the next sections.

Viewing the Word Object Model Diagram

To view the Word object model, open the Visual Basic window from a Word document, and type object model into the Answer box on the toolbar, then select Microsoft Word Objects to open the corresponding Help topic. The first page of the Word object model diagram from this Help topic opens, as shown in Figure 11.6.

click to expand
Figure 11.6

Some Help topics have their own subsidiary windows. Clicking the red triangle next to the Document object, for example, opens another Help window, shown in Figure 11.7.

click to expand
Figure 11.7

The Word object model is very extensive, and you can explore all of it by paging through the diagram in Help, and clicking on the red triangles to see more detail. However, when writing Automation code to work with Word, most likely you will be working with just a few components of this large and complex object model, primarily the Application object, the Documents, Templates, Tables, Bookmarks, and Styles collections, and perhaps the FileDialog and FileSearch objects.

Along with the diagrams in Help, there is another way to view the Word object model, which is generally more helpful when you are writing VBA code: Use the Object Browser, which is opened from the Visual Basic window of any Office component, using the F2 function key. This dialog lets you select objects and their properties, methods, and events, and open Help topics as needed. To view Word objects, select Word in the unlabeled Libraries selector at the upper left of the window. The Classes list contains objects, collections, and enumerations (abbreviated enums)—collections of named constants that can be used as argument values. When you make a selection in the Classes list, all the attributes of the selection object, collection, or enum are displayed in the Members list.

Figure 11.8 shows the properties and methods of the Bookmarks collection.

click to expand
Figure 11.8

On selecting a property, method, or event of an entry in the Classes list, you will see its syntax displayed in the Object Browser’s status bar. Figure 11.9 shows the syntax for the SetWidth method of the Column object. The method’s argument names (ColumnWidth and RulerStyle) are in italics, and for each argument, either its data type (Single) is given, or the enum used to select appropriate values (WdRulerStyle). For enum settings, you can click the enum name to open it and see the available selections.

click to expand
Figure 11.9

A Note on Enums

Enums (short for enumerations) are collections of named constants, used to set values of properties and method arguments of methods, or to check the return values of functions. If you have a reference set to the appropriate object model, you can use named constants that are members of an enum when writing code.

Using these named arguments for property values and arguments makes your code much more readable. For example, when writing Word Automation code:

gappWord.Selection.MoveDown unit:=wdLine, Count:=1, Extend:=wdExtend

is a lot more comprehensible than:

gappWord.Selection.MoveDown 5, 1, 1

However, there are circumstances where you need to use the numeric values for setting property and argument values:

  • When writing VBS code (such as the code behind Outlook forms). VBS code does not support most named constants, so you must use the numeric values instead.

  • When writing VBA code using late binding. In this type of code, variables are not declared as specific data types, and there may not be a reference set to the appropriate object model, so named constants won’t be recognized.

When you need to know the numeric (or other) values behind named constants, you can open an enum in the Object Browser, select the named constant whose value you need to know, and see its numeric value in the status bar, as shown in Figure 11.10.

click to expand
Figure 11.10

You can also search for an individual member of an enum (such as wdLine) in the Object Browser’s Search box to find out its value.

The Basic Automation Commands

To initiate an Automation session, you need to create an Automation object representing the Office component, in this case, Word. This is done by setting an object variable to the top-level Application object in the Word object model, using either the CreateObject or GetObject function. CreateObject creates a new instance of Word, while GetObject uses an existing instance of Word. To avoid creating extra Word instances, I like to use the GetObject function initially, with a fallback to CreateObject in a procedure’s error handler, so that an existing instance of Word will be used, if there is one, and a new instance will only be created if it is needed.

While you can use the GetObject function to create an instance of (say) a Word document, I find it more useful to create a Word application object that can then be used for all Automation work with Word, since most Automation code needs to work with properties and methods of the Application object itself, as well as properties and methods of lower-level objects such as the Document object. The syntax for setting a reference to an existing instance of Word, using the GetObject function, is:

Set gappWord = GetObject(, “Word.Application”)

If this line of code fails (because Word is not running), error 429 occurs, and the following error handler then runs a line of code using the CreateObject function to create a new instance of Word, and resumes running the code after the GetObject line.

ErrorHandler:

If Err.Number = 429 Then    ‘Word is not running; open Word with CreateObject    Set gappWord = CreateObject(“Word.Application”)    Resume Next Else    MsgBox “Error No: “ & Err.Number & “; Description: “    Resume ErrorHandlerExit End If

Using the gappWord variable, you can access any of the objects in the Word object model, to create documents and work with them as needed. The code samples in the “Exporting Access Data to Word Documents” and “Importing Data from Word Tables into Access” sections in this chapter (and the Word Data Exchange sample database) all use the gappWord variable as the starting point for working with various components of the Word object model.

To ensure that there is an instance of Word to work with, I run a function called OpenWord from the Word Data Exchange’s AutoExec macro, which uses GetObject to set the value of the global gappWord variable, if Word is running, and uses Shell to run Word in hidden mode otherwise (I use Shell instead of CreateObject here for pragmatic reasons—it works in Office 2000, XP, and 2003, while I have had some problems with CreateObject in 2003). The OpenWord function is listed below:

 Public Function OpenWord() On Error GoTo ErrorHandler        Set gappWord = GetObject(, "Word.Application")     ErrorHandlerExit:    Exit Function ErrorHandler:    If Err = 429 Then       ‘Word is not running; open Word with Shell       Shell "WinWord.exe", vbHide       Resume Next    Else       MsgBox "Error No: " & Err.Number & "; Description: " & Err.Description       Resume ErrorHandlerExit    End If End Function 

A Word VBA Shortcut

Word lets you record macros, so if you want to write VBA code to perform a certain action in Word, you can record a macro as follows: Turn the Word macro recorder on by double-clicking the REC button on the Word status bar, go through the steps you want to perform, and stop the recorder by clicking the Stop Recording button on the small Macro Recorder toolbar. The resulting saved macro (by default called Macron) contains the VBA code to do the steps you recorded. This code is likely to be verbose and in need of trimming (for example, you rarely need to assign a value to every single argument of a method), but it is very helpful as a preliminary step to writing Automation code.

The macro listed below was recorded from the following actions: Search for the first text formatted with the Comment style, and apply the Heading 4 style to that text (the replacement text came from a previous search and replace action):

 Sub Macro7()  ‘ Macro7 Macro ‘ Macro recorded 9/4/2003 by Helen Feddema     Selection.Find.ClearFormatting    Selection.Find.Style = ActiveDocument.Styles("Comment")    Selection.Find.ParagraphFormat.Borders.Shadow = False    With Selection.Find       .Text = ""       .Replacement.Text = "^p^mPrivate Function"       .Forward = True       .Wrap = wdFindContinue       .Format = True       .MatchCase = False       .MatchWholeWord = False       .MatchWildcards = False       .MatchSoundsLike = False       .MatchAllWordForms = False    End With    Selection.Find.Execute    Selection.Style = ActiveDocument.Styles("Heading 4") End Sub 

Trimmed of unnecessary argument settings and formatted with a With . . . End With structure for clarity, the code becomes:

    With Selection.Find       .ClearFormatting       .Style = ActiveDocument.Styles("Comment")       .Text = ""       .Execute    End With        Selection.Style = ActiveDocument.Styles("Heading 4") 




Expert One-on-One(c) Microsoft Access Application Development
Expert One-on-One Microsoft Access Application Development
ISBN: 0764559044
EAN: 2147483647
Year: 2006
Pages: 124
Authors: Helen Feddema

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net