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
'如果打开则获取现有的Word实例; 否则创建新的实例
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 = "完美Excel"
Set myDialog = oWord.Dialogs(wdDialogEditReplace)
With myDialog
.Find = "完美Excel"
.Replace = "excelperfect"
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
'释放
Set oWord = Nothing
Set oDoc = Nothing
Set myDialog = Nothing
'退出
Exit Sub
Err_Handler:
MsgBox "Word导致问题. " & Err.Description, vbCritical, "错误: " _
& Err.Number
If WordWasNotRunning Then
oWord.Quit
End If
End Sub