繁体   English   中英

EXCEL VBA在指定位置打开Word,编辑和Saveas。

[英]EXCEL VBA to Open Word, Edit and Saveas in the specified location.

我试图在指定位置打开Word应用程序,编辑,保存,并且需要检查用户是否输入了正确的文件名。 这是我的代码

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

现在,我在saveas文件中遇到了问题。 我使用了两种替代方法,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文章 ,“如果您将CreateObject函数与Word.Application或Word.Basic类型的对象一起使用,则如果Word已在运行,则该函数将失败。” 失败由运行时错误指示。 Microsoft建议您“检查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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM