Batch Template Changes

Written by Allen Wyatt (last updated November 26, 2016)
This tip applies to Word 97, 2000, 2002, and 2003


3

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.dot"

    ' 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/kb/224351"
        GoTo FinishUp
    End If

    'Get the template names
    strFindTemplate = UCase(InputBox("Name of template to find (exclude the .dot)") & _
      ".dot")

    strReplaceTemplate = InputBox("Name of replacement template (exclude the .dot)") & _
      ".dot"

    '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.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the WordTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (1437) applies to Microsoft Word 97, 2000, 2002, and 2003.

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

Changing Shapes in Microsoft Graph

Microsoft Graph allows you to define the shapes you use to represent data series. Here's how to do it.

Discover More

Using AutoText

AutoText is a timesaving feature that allows you to assign a word, phrase, paragraph, or graphic to a mnemonic name. Type ...

Discover More

Telling which Worksheets are Selected

If your macro processes information on a number of worksheets, chances are good that you need your macro to figure out ...

Discover More

The First and Last Word on Word! Bestselling For Dummies author Dan Gookin puts his usual fun and friendly candor back to work to show you how to navigate Word 2013. Spend more time working and less time trying to figure it all out! Check out Word 2013 For Dummies today!

More WordTips (menu)

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 ...

Discover More

Determining the Template Attached to a Document

If you've opened a document in Word, that document has a template attached to it. This tip looks at what those templates ...

Discover More

Creating a Boilerplate Document

If you have several boilerplate documents you need to routinely use in Word, then you should learn how to use templates. ...

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}] (all 7 characters, in the sequence shown) 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 two more than 7?

2018-01-24 12:30:13

Josh

i was able to answer my previous question, and added to your first macros:from https://blogs.msdn.microsoft.com/ericwhite/2010/01/27/programmatically-limiting-styles-in-word/place inside existing loop in first macrosDo While strCurDoc <> ""' lock all stylesDim cnt As IntegerFor Each Style In docCurDoc.StylesStyle.Locked = TrueNext ' unlock specific stylesdocCurDoc.Styles("Heading 1").Locked = False' automatically update styles on opendocCurDoc.UpdateStylesOnOpen = TrueLoop


2018-01-24 10:16:12

Josh

this is really helpful for my project. i have nearly 100 documents in multiple directories that this helps streamline. but i have 1 more step that i can't figure out. 1. my template styles are restricted to headings 1-3, bulleted + numbered lists, hyperlink, and normal. i've hidden all other styles2. if i double click on the template file to start a new document, this works as planned. restricted styles are all present and nothing else3. if i run the 1st macros above for Batch Template Changes, it changes the template as it should, with permitted styles listed. however, if there are custom styles present in the document, those will stay alongside my permitted styles. this happens with existing documents as well when i copy and paste text into a file based on my template. Q: how do i remove/hide/restrict all styles that aren't in my permitted styles list?Q: is it possible to make the Batch Template Changes macros recursive for all sub-directories?


2017-05-15 11:27:01

Sean

I found that ChangeTemplates() needs a change in the strCurDoc assignment. A backslash is necessary otherwise the file extension is appended to the directory name.

Thanks for all your great tips!

-sean-


This Site

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

Videos
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.