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

Reliable Conversion to WordPerfect

If you have documents that you need to save in WordPerfect format, you might experience some frustration in making the ...

Discover More

Using Drag-and-Drop to Create a Hyperlink

If you open workbooks in two instances of Excel, you can use drag-and-drop techniques to create hyperlinks from one ...

Discover More

Setting Row Height

When you enter information into a row on a worksheet, Excel automatically adjusts the height of the row based on what you ...

Discover More

Create Custom Apps with VBA! Discover how to extend the capabilities of Office 2013 (Word, Excel, PowerPoint, Outlook, and Access) with VBA programming, using it for writing macros, automating Office applications, and creating custom applications. Check out Mastering VBA for Office 2013 today!

More WordTips (menu)

Understanding Templates

Templates are used to store a pattern for how a document should look. As such, they can be a very powerful tool for ...

Discover More

Editing a Template

Editing a template can be as easy as editing a regular Word document, provided you know where to find the templates. Here ...

Discover More

Changing the Attached Template

Templates, when attached to a document, can greatly affect how that document looks. You can change from one template to ...

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 2 + 2?

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.