参考: Private Sub Command1_Click() On Error GoTo connecterr Dim wordApp As Object Set wordApp = CreateObject("word.application") wordApp.Visible = True Dim myDoc As Object 'Set myDoc = wordApp.Documents.Add Set myDoc = wordApp.Documents.Open(App.Path & "\test.doc") wordApp.selection.TypeText (" Hello") MsgBox "a" wordApp.selection.TypeText (" Hello@@") myDoc.Close wordApp.Quit Set myDoc = Nothing Set wordApp = Nothing Exit Sub connecterr: If Err.Number = 5174 Then MsgBox "文件不存在!" If Err.Number = 462 Then MsgBox "操作对象已经关闭!" End Sub
public gWordApp as objectpublic function wordApp as object on error goto err set wordApp =gWordApp exit fucntion err: Set gWordApp = CreateObject("word.application") resume 0 end function
Private Sub Command1_Click()
On Error GoTo connecterr
Dim wordApp As Object
Set wordApp = CreateObject("word.application")
wordApp.Visible = True
Dim myDoc As Object
'Set myDoc = wordApp.Documents.Add
Set myDoc = wordApp.Documents.Open(App.Path & "\test.doc")
wordApp.selection.TypeText (" Hello")
MsgBox "a"
wordApp.selection.TypeText (" Hello@@") myDoc.Close
wordApp.Quit
Set myDoc = Nothing
Set wordApp = Nothing
Exit Sub
connecterr:
If Err.Number = 5174 Then MsgBox "文件不存在!"
If Err.Number = 462 Then MsgBox "操作对象已经关闭!"
End Sub
on error goto err
set wordApp =gWordApp
exit fucntion
err:
Set gWordApp = CreateObject("word.application")
resume 0
end function