11

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?

Here is my code:

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
pnuts
  • 58,317
  • 11
  • 87
  • 139
Brian
  • 715
  • 4
  • 16
  • 37

2 Answers2

11

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)
Valiante
  • 1,176
  • 1
  • 9
  • 15
8

If you indicate that the file is ReadOnly while setting the file name, and you turn off alerts, this should solve the issue of the prompt:

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

And when you go to save the file, just save it with the ".doc" file extension instead of ".dot" so its saved as a word file type. You can also change the file name and output directory path if you so choose. (Also, remember to turn the alerts back on)

With wDoc

.ActiveDocument.SaveAs Filename:="C:\Documents\NewWordDocumentFromTemplate.doc"

End With

wApp.DisplayAlerts = True

Hope this helps!

wahwahwah
  • 3,254
  • 1
  • 21
  • 40