Changing the attached document

G

Gary Hillerson

I have a situation where I want to change the template (from TemplateA
to TemplateB) attached to the active document, and then save and close
the document. When I subsequently reopen it, it should be based on the
new template (TemplateB)

I can do exactly this using Word's menus and all's well.
- open the document, then go to Tools|Templates and Add-ins
- click Attach and select a different template
- Save and Close the document

So I want to put the code in TemplateA that emulates using the menu
system. I did this:

Public Sub ChangeTemplate
With ActiveDocument
MsgBox "Change template from" & .AttachedTemplate
.AttachedTemplate = "C:\MyTemplates\TemplateB.dot"
MsgBox "Changed template to TemplateB.dot"
.Close saveChanges:=wdSaveChanges
End With
End Sub

Then I create mydoc.doc, based on TemplateA.dot and save it. Then I
execute the ChangeTemplate Function. And as soon as I change the
..AttachedTemplate property of the ActiveDocument, things get wacky.
The code that follows that statement (the MsgBox and Close) don't
execute.

If I then tell Word to save and close the document, when I reopen the
doc, Word immediately asks if I want to save it. If I say yes, it
closes the doc. If I say no, it closes the doc. If I cancel, I get an
error 4198.

Whew! I think I'm screwing VBA's state and clearly I'm messing up the
document..

Can anyone help with this function?

thanks in advanc,
gary
 
J

Julie

Gary,

Your code to change the attached template needs to live in a global
template, not Template A. I did not try your code out, but it makes sense
that it would cause things to go sideways. By attaching the document to
Template B, you effectively unload Template A from memory at a time when a
Template A Macro A is in progress.

I have global code that routinely reattaches documents to templates for
hundreds of users without incident. That code lives in a global template.

If running the code from a global template, before programmatically
reattaching the document to the target template, you should have the code
test to make sure that the document is not already attached to the target
template. Things can also go sideways if you attempt to programmatically
change the attachment to the existing attached template.
Hope this helps,
Julie
 
G

Gary Hillerson

Thanks Julie. I sort of figured that was the case (and it does make
sense). Unfortunately, I can't use a global tempalte in my situation
(complicated story), so I'll just tell users how to do this via Word's
menu system.

Thanks for your help

gary
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top