用Excel VBA打开Word模板,填充内容,然后将其另存为.docx文件到其他地方。

11

我创建了一个带有占位符(例如<>)的Word模板,然后可以使用我的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
2个回答

11

@wahwahwah的方法虽然可行,但仍需要将模板作为文档打开并进行编辑,然后以另一种格式保存,同时抑制警报。我猜想您想要实现的是从shell中打开模板时生成基于模板的“新”文档的行为。您可以使用“Add”方法来实现这一点,如下所示:

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

8
如果你在设置文件名时指定文件为只读(ReadOnly),并关闭警告提示,这将解决提示问题。
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

希望这能帮到您!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接