Excel VBA打开Word模板,填充,然后另存为.docx文件 [英] Excel VBA to open word template, populate, then save as .docx file somewhere else
问题描述
我创建了一个带有<>等占位符的单词模板,然后可以用excel宏自动替换它.当我再次尝试此过程时,现在会打开文档一词,表示它是只读文档.我应该如何保存我的Word模板以便可以对其进行编辑?另外,当我通过excel宏打开Word模板时,如何知道将其另存为新的Word文档而不是将其另存为更新的模板?
I created a word template with placeholders such as <> that I am then able to replace automatically with my excel macro. When I tried this process again, the word document now opens saying it is a read only document. How am I supposed to save my Word Template so it can be edited? Also, when I open the word template through my excel macro, how does it know to save it as a new word document, and not save it as an updated template?
这是我的代码:
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
推荐答案
@wahwahwah的方法有效时,它仍将模板作为文档打开以进行编辑,然后以其他格式保存该模板,同时禁止显示警报.我怀疑您想要实现的是从外壳打开模板时的行为,该行为会基于模板生成新"文档.您可以通过"添加"方法来实现;
While @wahwahwah's approach works, it is still opening the template as a document for editing, then saving it in another format, while suppressing alerts. What I suspect you want to achieve is the behaviour when opening a template from the shell, which generates a "new" document based on the template. You can achieve this with the "Add" method thus;
Set wDoc = wApp.Documents.Add(Template:="file path here", NewTemplate:=False, DocumentType:=0)
这篇关于Excel VBA打开Word模板,填充,然后另存为.docx文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!