EXCEL VBA在指定位置打开Word,Edit和Saveas。
问题描述:
我试图在指定位置打开Word应用程序,编辑,保存并需要检查用户是否输入了正确的文件名。 这里是我的代码EXCEL VBA在指定位置打开Word,Edit和Saveas。
Dim Doc
Dim DocPath
Dim DocObj
Dim VarResult
DocPath = "C:\MyFolder\MyDocument.doc"
Set DocObj = CreateObject("word.Application")
Doc = DocObj.Documents.Open(DocPath)
DocObj.Visible = True
打开文档后,我做了一些变化
With Doc.ActiveDocument
Set myRange = .Content
With myRange.Find
.Execute FindText:="FindText", ReplaceWith:="ReplaceText", Replace:=2
End With
End With
现在,我已经在另存为一个问题的文件。我使用了两种替代方法: 1:GetSaveAsFilename,2:SaveAs。我需要显示Saveas对话框(使用所有DefaultLocation,InitialFilename,DocumentType,Title属性)。用户需要选择和需要验证的相同,无论用户是否没有给出取消按钮。
varResult = Doc.GetSaveAsFilename(_
FileFilter:="DP Document (*.doc), *.doc, DP Document (*.docx), *.docx", Title:="Save DP", initialvalue:="InitialDocument")
If varResult <> False Then
MsgBox "File choosen = " & varResult
Else
MsgBox "Please select the file"
End If
我得到运行时错误。提前致谢。
答
根据此Microsoft Article,“如果您使用CreateObject函数与Word.Application或Word.Basic类型的对象,该函数将失败,如果Word已在运行。”失败由运行时错误指示。微软建议你“检查Word是否已经在运行,如果没有,请启动一个新的Word实例。”例如,您可以使用“GetObject函数创建一个Word.Application对象,如果GetObject函数失败,Word将不会运行,因此CreateObject函数将用于设置Word.Application对象。”链接文章中提供的代码如下:
Sub RunWord()
Dim wObj As Word.Application
On Error Resume Next
' Get existing instance of Word if it exists.
Set wObj = GetObject(, "Word.Application")
If Err <> 0 Then
' If GetObject fails, then use CreateObject instead.
Set wObj = CreateObject("Word.Application")
End If
' Add a new document.
wObj.Documents.Add
' Exit Word.
wObj.Quit
' Clear object memory.
Set wObj = Nothing
End Sub