【问题标题】:Excel VBA to open word template, populate, then save as .docx file somewhere elseExcel VBA 打开 word 模板,填充,然后在其他地方另存为 .docx 文件
【发布时间】:2018-04-09 19:08:34
【问题描述】:

我创建了一个带有诸如 之类的占位符的单词模板,然后我可以用我的 excel 宏自动替换它。当我再次尝试此过程时,word 文档现在打开,说它是只读文档。我应该如何保存我的 Word 模板以便对其进行编辑?还有,当我通过我的excel宏打开word模板时,它怎么知道是保存为新的word文档,而不是保存为更新的模板?

这是我的代码:

Sub ReplaceText()
Dim wApp As Word.Application
Dim wDoc As Word.Document
Set wApp = CreateObject("Word.Application")
wApp.Visible = True

Set wDoc = wApp.Documents.Open("file name here")

With wDoc
    .Application.Selection.Find.Text = "<<name>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("A5")
    .Application.Selection.EndOf

    .Application.Selection.Find.Text = "<<dob>>"
    .Application.Selection.Find.Execute
    .Application.Selection = Range("A6")

    .SaveAs2 Filename:=("file name goes here"), _
    FileFormat:=wdFormatXMLDocument, AddtoRecentFiles:=False
End With

End Sub

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    虽然@wahwahwah 的方法有效,但它仍将模板作为文档打开以进行编辑,然后将其保存为另一种格式,同时抑制警报。我怀疑你想要实现的是从外壳打开模板时的行为,它会基于模板生成一个“新”文档。因此,您可以使用“Add”方法实现此目的;

    Set wDoc = wApp.Documents.Add(Template:="file path here", NewTemplate:=False, DocumentType:=0)
    

    【讨论】:

      【解决方案2】:

      如果你在设置文件名的时候指明文件是ReadOnly,并且你关闭了alert,这样应该可以解决提示的问题:

      Set wApp = CreateObject("Word.Application")
      wApp.DisplayAlerts = False
      Set wDoc = wApp.Documents.Open Filename:="C:\Documents\SomeWordTemplate.dot", ReadOnly:=True
      

      当您保存文件时,只需使用“.doc”文件扩展名而不是“.dot”保存它,以便将其保存为 word 文件类型。如果您愿意,还可以更改文件名和输出目录路径。 (另外,记得重新打开警报)

      With wDoc
      
      .ActiveDocument.SaveAs Filename:="C:\Documents\NewWordDocumentFromTemplate.doc"
      
      End With
      
      wApp.DisplayAlerts = True
      

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多