Copy all styles from a template using VBA

S

Staroslav

I am trying to write a macro that copies all existing styles from a given
template to an active document. Can't get it to work because Word requires
that I give a name for each style I want to copy. I know it's doable, just am
having problems figuring out the code for it.
Thanks ahead of time for your help!

Below is what I have, but it doesn't work:

Sub CopyAllStyles()
'
Dim SDoc As Document, strDDoc, strSDoc, nStile As String, Stil As Style, S
As Long
strDDoc = ActiveDocument.FullName
strSDoc = "C:\Documents and Settings\Myself\Application
Data\Microsoft\Templates\MyTemplate.dot"

On Error Resume Next
For S = 1 To SDoc.Styles.Count
nStil = SDoc.Styles(S).NameLocal
Application.OrganizerCopy Source:=strSDoc, Destination:=strDDoc, _
Name:=nStil, Object:=wdOrganizerObjectStyles
Next S

End Sub
 
S

Staroslav

Well, I guess it is because I am too lazy to do it for every single document
I have to work with (there are lots of them). I didn't get into the reasons
for why, because it would take a good deal of explanation. I hope it will be
sufficient to say that this procedure is part of a larger document
preparation macro that goes through a number of steps, and copying styles is
just one of them. Do you know how to???
 
T

Tom Winter

I haven't done exactly what you are doing, but I though this code my
help....(OpenDocument() and CloseDocument() are just my error handling
wrappers around Documents.Open and Document.Close. There's nothing special
about them.)

Public Sub CopyAllAutoText(oWord As Word.Application, sSrcFileSpec As
String, sDstFileSpec As String)

On Error GoTo ErrorHandler

Dim oSrcDocument As Word.Document

Dim oSrcTemplate As Word.Template

Dim oAutoTextEntry As Word.AutoTextEntry

Set oSrcDocument = OpenDocument(oWord, sSrcFileSpec)

Set oSrcTemplate = oSrcDocument.AttachedTemplate

For Each oAutoTextEntry In oSrcTemplate.AutoTextEntries

CopyAutoText oWord, sSrcFileSpec, sDstFileSpec,
oAutoTextEntry.Name

Next

CloseDocument oSrcDocument

Exit Sub

ErrorHandler:

CloseDocument oSrcDocument

' Do something with the error

End Sub

Public Sub CopyAutoText(oWord As Word.Application, sSrcFileSpec As String,
sDstFileSpec, sName As String)

On Error GoTo ErrorHandler

oWord.OrganizerCopy sSrcFileSpec, sDstFileSpec, sName,
wdOrganizerObjectAutoText

Exit Sub

ErrorHandler:

' Do something with the error

End Sub
 
C

Charles Kenyon

Note that you will want to run the copy cycle three times to preserve links
between styles.
 
S

Staroslav

Thank you Tom and Charles for the hints. I spent some time trying to get
Tom's code to work, but so far, no success. My VBA knowledge is rather basic,
I am afraid. Still looking for a solution.
 

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