Excel VBA打开word模板,填充,然后另存为.docx文件

我创build了一个带有占位符(如<>>)的单词模板,然后我可以用我的Excelmacros自动replace。 当我再次尝试这个过程时,现在文档文档打开,说它是一个只读文档。 我该如何保存我的Word模板以便编辑? 此外,当我通过我的Excelmacros打开单词模板时,如何知道将它保存为新的单词文档,而不是将其另存为更新的模板?

这是我的代码:

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 

如果在设置文件名时指出文件是ReadOnly,并且closures了警报,则应该解决提示问题:

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

而当你去保存文件时,只需要用“.doc”文件扩展名而不是“.dot”来保存它,这样它就可以保存为文件types。 如果您愿意,也可以更改文件名和输出目录path。 (另外,请记住重新打开警报)

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

希望这可以帮助!