Please Note: This article is written for users of the following Microsoft Word versions: 2007, 2010, 2013, and 2016. If you are using an earlier version (Word 2003 or earlier), this tip may not work for you. For a version of this tip written specifically for earlier versions of Word, click here: Batch Template Changes.

Batch Template Changes

by Allen Wyatt
(last updated November 28, 2015)

4

Templates are used to quickly define a standard look for a document or a group of documents. The wonderful thing about templates is that you can define one template to give your document one look, and another template to give it an entirely different look. All you need to do, of course, is change which template is associated with a document.

Changing the template associated with one or two documents is quite easy. What if you have a directory full of documents whose templates need to be changed? This can get quite tedious very quickly. This is where a macro can come to the rescue—to relieve that old tedium and do the mundane very quickly. The following macro, ChangeTemplates, modifies all the documents in a particular directory to make sure they use the template you want.

Sub ChangeTemplates()
    Dim strDocPath As String
    Dim strTemplateB As String
    Dim strCurDoc As String
    Dim docCurDoc As Document

    ' set document folder path and template strings
    strDocPath = "C:\path to document folder\"
    strTemplateB = "C:\path to template\templateB.dotx"

    ' get first doc - only time need to provide file spec
    strCurDoc = Dir(strDocPath & "*.doc?")

    ' ready to loop (for as long as file found)
    Do While strCurDoc <> ""
        ' open file
        Set docCurDoc = Documents.Open(FileName:=strDocPath & strCurDoc)
        ' change the template
        docCurDoc.AttachedTemplate = strTemplateB
        ' save and close
        docCurDoc.Close wdSaveChanges
        ' get next file name
        strCurDoc = Dir
    Loop
    MsgBox "Finished"
End Sub

In order to use the macro, simply make sure that the strDocPath and strTemplateB variables are set properly. The macro changes the template associations for all documents in a particular directory. If you want something a little more discriminating, then a different macro is in order. For instance, you may want to have the macro examine each document and only change those that use TemplateA so that they now use TemplateB. In this instance you will find the following macro very handy:

Sub TemplateBatchChange()
    Dim objPropertyReader
    Dim strFolder As String
    Dim strFileName As String
    Dim objThisDoc As Word.Document
    Dim strFindTemplate As String
    Dim strReplaceTemplate As String
    Dim strAffectedDocs As String

    On Error Resume Next

    'Create the PropertyReader object
    Set objPropertyReader = CreateObject("DSOleFile.PropertyReader")
    If Err.Number <> 0 Then
        MsgBox "You must install the DSOleFile component. See " & _
          "http://support.microsoft.com/?kbid=224351"
        GoTo FinishUp
    End If

    'Get the template names
    strFindTemplate = UCase(InputBox("Name of template to find"))
7
    strReplaceTemplate = InputBox("Name of replacement template")

    'Make sure it's a valid template. Try to create a new document based on it.
    Set objThisDoc = Word.Documents.Add(strReplaceTemplate, Visible:=False)
    If Err.Number <> 0 Then
        'No such template
        MsgBox "There is no accessible template named " & strReplaceTemplate
        GoTo FinishUp
    End If
    'Close the test document
    objThisDoc.Close wdDoNotSaveChanges

    On Error GoTo ErrorHandler
    'Get the current documents path
    strFolder = Word.Application.Options.DefaultFilePath(wdDocumentsPath) _
      & Word.Application.PathSeparator

    'Examine all Word documents in the directory

    'Get the first document name
    strFileName = Dir(strFolder & "*.doc?")

    While strFileName <> ""
        'Look at the template name
        If UCase(objPropertyReader.GetDocumentProperties _
          (strFolder & strFileName).Template) = strFindTemplate Then

            'It matches. Open the document
            Set objThisDoc = Word.Documents.Open _
              (FileName:=strFileName, Visible:=False)

            'Change the attached template
            objThisDoc.AttachedTemplate = strReplaceTemplate

            'Save the change
            objThisDoc.Close wdSaveChanges

            'Note the document
            strAffectedDocs = strAffectedDocs & strFileName & ", "
        End If
        'Get the next document
        strFileName = Dir
    Wend

    'Report the results
    If strAffectedDocs = "" Then
        MsgBox "No documents were changed.", , "Template Batch Change"
    Else
        'Remove the trailing comma and space
        strAffectedDocs = Left(strAffectedDocs, Len(strAffectedDocs) - 2)

        MsgBox "These documents were changed: " & _
          strAffectedDocs, , "Template Batch Change"
    End If
    GoTo FinishUp

ErrorHandler:
    Set objThisDoc = Nothing
    Set objPropertyReader = Nothing
    Err.Raise vbError + 1001, "TemplateBatchChange", _
      "TemplateBatchChange encountered an error: " & Err.Description

FinishUp:
    'Release object references
    Set objThisDoc = Nothing
    Set objPropertyReader = Nothing
End Sub

In order to use this macro, you must first make sure that the DSOLEFILE component (available free from Microsoft) is installed on your system. You can find out more about this component by referring to Microsoft's 224351 Knowledge Base article. The macro provides you a chance to specify a template name to be replaced and the name of the template to replace it with. It even checks to make sure that the replacement template exists.

This macro searches for documents in the default Word document folder. If you want to search in a different directly, you should make sure that the strFolder variable gets set to the full path of the folder you want used.

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (10338) applies to Microsoft Word 2007, 2010, 2013, and 2016. You can find a version of this tip for the older menu interface of Word here: Batch Template Changes.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Adding Paragraph Numbering

You may search high and low for a way to add automatic numbers to paragraphs in a document. You won't find the capability, ...

Discover More

Quickly Moving Text with the Mouse

Drag-and-drop editing is a handy feature when you love to use the mouse. There are two ways you can move text using the ...

Discover More

Changing How Footnote References Appear

Footnote references normally appear as superscripted digits, both in the main body of your document and in the footnotes ...

Discover More

Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing macros in all Office programs. This complete guide shows both professionals and novices how to master VBA in order to customize the entire Office suite for their needs. Check out Mastering VBA for Office 2010 today!

More WordTips (ribbon)

Quick Access Toolbars and Templates

Want to create a customized Quick Access Toolbar and associate that toolbar with a particular template? The task is easier ...

Discover More

Templates and Page Setup

Templates are a great way to share styles, macros, and other settings among various documents. One thing that isn't shared ...

Discover More

Finding Where Templates Are Stored

The first step in modifying templates is to find out where they are stored on your system. Here's the easiest way to figure ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 6 - 0?

2016-02-15 19:17:46

John T

Hello,
I'm trying to batch update all my watermarks with a new watermark.
First macro updates the template but doesn't touch the watermark.
With your second macro, I'm running into issues with DSOleFile. Installed and registered but errors every time I try to run it.

Thanks,
John


2016-02-12 09:50:10

David Mogg

Noticed Amanda's comment so ran it in the template; works fine.

Sorry to have been a pain and thanks for a great macro.


2016-02-12 09:43:11

David Mogg

Further info re my previous comment. Ran the bat file from the cmd prompt and got;
Microsoft Windows [Version 10.0.10586]
(c) 2015 Microsoft Corporation. All rights reserved.

C:Windowssystem32>cd C:UsersDavidLinks

C:UsersDavidLinks>$ChangeTemplate.bat

C:UsersDavidLinks>Sub ChangeTemplates()
'Sub' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>Dim strDocPath As String
'Dim' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>Dim strToxRep As String
'Dim' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>Dim strCurDoc As String
'Dim' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>Dim docCurDoc As Document
'Dim' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>' set document folder path and template strings
''' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>strDocPath = "C:UsersDavidDocumentsToiletriesRaw MaterialsHair Dyes"
'strDocPath' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>strToxRep = "C:UsersDavidAppDataRoamingMicrosoftTemplatesToxRep.dotx"
'strToxRep' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>' get first doc - only time need to provide file spec
''' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>strCurDoc = Dir(strDocPath & "*.docx")
'strCurDoc' is not recognized as an internal or external command,
operable program or batch file.
'"*.docx")' is not recognized as an internal or external command,
operable program or batch file.

C:UsersDavidLinks>' ready to loop (for as long as file found)
''' is not recognized as an internal or external command,
operable program or batch file.
> was unexpected at this time.

C:UsersDavidLinks> Do While strCurDoc <> ""

C:UsersDavidLinks>

Using Word 2007 in Windows 10.


2016-01-26 09:17:39

Amanda

Hey, this is great! I have over 2,000 templates to apply and can't wait to use this.
I'm not sure I understand where this macro lives to make it run, though? Do I put the macro inside the template?

Thanks!


This Site

Got a version of Word that uses the ribbon interface (Word 2007 or later)? This site is for you! If you use an earlier version of Word, visit our WordTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.