Control Word from Excel
Article contributed by Bill Coan Bill Coan and Dave Rado
Here's some code which uses Early Binding. It checks to see if Word is running. If it is, the code uses the existing instance of Word. If not, the code creates an instance of Word.
First set a reference to Word (in the VB Editor, select Tools + References).
Sub ControlWordFromXL()
Dim oWord
As Word.Application
Dim WordWasNotRunning
As Boolean
Dim oDoc As
Word.Document
Dim myDialog As
Word.Dialog
Dim UserButton As
Long
'Get existing instance of Word if it's open; otherwise
create a new one
On Error Resume Next
Set oWord = GetObject(, "Word.Application")
If Err Then
Set oWord = New
Word.Application
WordWasNotRunning = True
End If
On Error GoTo Err_Handler
oWord.Visible = True
oWord.Activate
Set oDoc = oWord.Documents.Add
oDoc.Range.Text = "Hi"
Set myDialog =
oWord.Dialogs(wdDialogEditReplace)
With myDialog
.Find = "Hi"
.Replace = "Ho"
End With
On Error Resume Next
UserButton = myDialog.Display()
On Error GoTo Err_Handler
MsgBox "User Button = " & CStr(UserButton)
MsgBox "Find = " & CStr(myDialog.Find)
MsgBox "Replace = " & CStr(myDialog.Replace)
MsgBox "Direction = " & CStr(myDialog.Direction)
MsgBox "Wrap = " & CStr(myDialog.Wrap)
MsgBox "Format = " & CStr(myDialog.Format)
MsgBox "MatchCase = " & CStr(myDialog.MatchCase)
MsgBox "WholeWord = " & CStr(myDialog.WholeWord)
MsgBox "PatternMatch = " & CStr(myDialog.PatternMatch)
MsgBox "FindAllWordForms = " & CStr(myDialog.FindAllWordForms)
MsgBox "SoundsLike = " & CStr(myDialog.SoundsLike)
MsgBox "FindNext = " & CStr(myDialog.FindNext)
MsgBox "ReplaceOne = " & CStr(myDialog.ReplaceOne)
MsgBox "ReplaceAll = " & CStr(myDialog.ReplaceAll)
MsgBox "MatchByte = " & CStr(myDialog.MatchByte)
MsgBox "FuzzyFind = " & CStr(myDialog.FuzzyFind)
MsgBox "Destination = " & CStr(myDialog.Destination)
oDoc.Close savechanges:=wdDoNotSaveChanges
If WordWasNotRunning
Then
oWord.Quit
End If
'Make sure you release object references.
Set oWord = Nothing
Set oDoc = Nothing
Set myDialog = Nothing
'quit
Exit Sub
Err_Handler:
MsgBox "Word caused a problem. " & Err.Description,
vbCritical, "Error: " _
&
Err.Number
If WordWasNotRunning
Then
oWord.Quit
End If
End Sub