HOWTO: Run a Word 97 Macro That Requires Arguments
ID: Q172483
|
The information in this article applies to:
-
Microsoft Visual Basic Learning, Professional, and Enterprise Editions for Windows, versions 5.0, 6.0
-
Microsoft Visual Basic Standard, Professional, and Enterprise Editions for Windows, version 4.0
-
Microsoft Office 2000 Developer
-
Microsoft Word 2000
-
Microsoft Word 97 for Windows
SUMMARY
When using Microsoft Word 97 or Word 2000 as an ActiveX server, you can run a Word VBA
macro by using Word's Run method. However, the Run method cannot be used
with automation to run a Word macro that requires arguments. To run a Word
macro that requires arguments, you can make your Word macro a method of
your document or template. This article illustrates how to do this.
MORE INFORMATION
To make a macro act as a method for your document or template, add the
macro as a Public Sub to the ThisDocument object in the Visual Basic Editor
for Word.
The following steps demonstrate how to create a Visual Basic application
that executes a custom method of a Word document. This method expects two
arguments, a string and an integer.
Steps to Create the Word Macro
- Start a new Word document (Document1).
- Press ALT+F11 to start the Visual Basic Editor.
- Click Project Explorer on the View menu to display the Project Explorer.
- In the Project Explorer, locate the "ThisDocument" object for
Document1's project. Right-click "ThisDocument" and select View Code.
- In the code window for ThisDocument, add the following macro:
Public Sub Macro1(s As String, i As Integer)
MsgBox s 'Display the string
MsgBox i * 10 'Display the product i and 10
End Sub
- Press ALT+Q to exit the Visual Basic Editor and return to Document1.
- Save this document as C:\TEST.DOC, and exit Word.
Steps to Create the Visual Basic Application
- Start a new "Standard EXE" project.
- On the Project menu, click References. For Word 97, check "Microsoft Word 8.0 Object
Library," and click OK. For Word 200, check "Microsoft Word 9.0 Object Library.
- Add the following code to Form1.
Option Explicit
Dim objWordApp As Word.Application
Dim objWordDoc As Word.Document
Private Sub Form_Click()
'Create a new instance of Word
Set objWordApp = New Word.Application
'Open the document containing the macro
Set objWordDoc = _
objWordApp.Documents.Open("C:\TEST.DOC")
'Run the macro
objWordDoc.macro1 "Hello!", 23
'Close the document and clear the variables
objWordDoc.Close
Set objWordDoc = Nothing
Set objWordApp = Nothing
End Sub
- Press the F5 key to run the application. Click Form1 to run the Word
macro.
Additional query words:
Keywords : kbinterop kbAutomation KbVBA kbVBp kbVBp400 kbVBp500 kbVBp600 kbWord kbGrpDSO kbOffice2000 kbword2000
Version : WINDOWS:2000,4.0,5.0,6.0,97; :
Platform : WINDOWS
Issue type : kbhowto
|