By using Automation code in Microsoft Access, you can open a Microsoft Word
2000 document and run a macro in the document.
The following examples use two methods, one that opens a Word 2000 document that is external to Access, and one that opens a document that is embedded in an Access form.
These examples assume that you have installed Word 2000, that you have created a document called WordTest.doc (on drive C), and that a macro called Macro1 exists in the default template (Normal.dot).
Example 1: Run a Macro in an External Microsoft Word 2000 Document
- Start Microsoft Access and open any database or project.
- In the Database window, click Modules, and then click New.
- On the Tools menu, click References.
- Click Microsoft Word 9.0 Object Library in the Available References box, and then click OK.
- Type or paste the following procedure in the module:
Function RunWordMacro()
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open _
("C:\Wordtest.doc")
WordApp.Visible = True
WordApp.Run "Macro1"
' Uncomment the next line of code to print the document.
' WordDoc.PrintOut Background:=False
' Uncomment the next line of code to save the modified document.
' WordDoc.Save
WordApp.Quit SaveChanges:=wdDoNotSaveChanges
Set WordApp = Nothing
End Function
- To test this function, type the following line in the Immediate window, and then press ENTER:
?RunWordMacro()
Note that Microsoft Word opens the Wordtest.doc document on drive C, and then runs the macro called Macro1.
Example 2: Run a Macro in an Embedded Microsoft Word 2000 Document
- Start Microsoft Access and open any database or project.
- In the Database window, click Modules, and then click New.
- On the Tools menu, click References.
- Click Microsoft Word 9.0 Object Library in the Available References box, and then click OK.
- On the File menu, click Close and Return to Microsoft Access.
- In the Database window, click Forms, and then click New.
- Add an unbound object frame control to the Detail section of the form.
- In the Insert Object dialog box, click Create from File, and then, in the File box, type the path and location of the Word file with the macro. For this example, type the following path in the File box:
C:\WordTest.doc
- Set the following properties for the unbound object frame control:
Name: MacroObj
Locked: No
- Add a command button to the form, and then set its Name property to RunWordMacro. Set its On Click property to the following event procedure:
Private Sub RunWordMacro_Click()
Dim WordObj As Word.Application
' Open Microsoft Word 97 in place and activate it.
Me![MacroObj].Verb = -4
Me![MacroObj].Action = 7
Set WordObj = Me![MacroObj].Object.Application
WordObj.Run "Macro1"
Set WordObj = Nothing
End Sub
- On the View menu, click Form View.
- Click the command button on the form, and then note that the macro runs while the document is edited in place in the control on your form.