0
votes

I wrote a macro in VBA MS Word to automatically attaching template in new document:

Sub AutoNew()
    ActiveDocument.AttachedTemplate = <Path To Template>
    ActiveDocument.UpdateStylesOnOpen = True
End Sub

However, this macro doesn't work properly. It attaches the template, macros in the template work, but it doesn't update styles. Only styles from the Normal template are available. Could you tell me what can I do? Thanks in advance

2
Cross-posted at: msofficeforums.com/word-vba/…. For cross-posting etiquette, please read: excelguru.ca/content.php?184macropod

2 Answers

0
votes

When a new document is created the styles from the template it was based on are copied to the document.

When you attach a template and update styles only the styles that are flagged as in use will be updated.

The purpose of UpdateStylesOnOpen is to either:

  1. update the styles in a document because the template it was originally based on has been updated.
  2. overwrite changes the user has made to styles in the document.

So if you want a new document to contain the correct styles you should start by creating it from the correct template.

EDIT:

AutoNew will affect every new document however it is created, so if it is your intention that all new documents are based on a specific template a better approach would be to intercept the FileNewDefault command (New File icon on the Quick Access Toolbar or Ctrl+N).

Public Sub FileNewDefault
    Documents.Add Template:=<path to template>
End Sub

If you insist on treating the effect rather than tackling the cause then you can modify AutoNew as follows:

Public Sub AutoNew
    ActiveDocument.AttachedTemplate = <Path To Template>
    ActiveDocument.UpdateStyles
End Sub

However, if you do take this approach you should first read the Word MVP's article on UpdateStyles to ensure that you understand the limitations of this approach.

0
votes

Reverse the order of your commands. You need to tell the document to update the styles from the template and then attach it.

I would recommend:

Sub AutoNew()
    Let ActiveDocument.UpdateStylesOnOpen = True
    Let ActiveDocument.AttachedTemplate = <Path To Template>
    Let ActiveDocument.UpdateStylesOnOpen = False ' Once styles are imported, turn off this attribute
End Sub
  • Note the ending turning that setting off. This is a poor setting to keep active and it stays with the document.

Like Timothy Rylatt, I am wondering why you are not simply starting the document based on the relevant template. Then the styles are already there.