adding vba code to several word documents

W

Werner Pertl

hi all!
i've written a few lines of vba code which i now want to add to about 100
word documents.
does someone have an idea how to automate this job?
thank you very much in advance.
werner
 
S

Steve Lang

Hi Werner,

Add the code to a template, then link your documents to your new template.
That way, if there are any changes to the code, you only change it in one
place, and all documents based on that template reflect your changes.

HTH and have a great day!

Steve
 
K

Klaus Linke

If the code can/should be available for all documents, you can also add the
template as a global template (Tools > Templates and Add-ins).

Regards,
Klaus
 
W

Werner Pertl

Thanks for your answers so far :)

But is there a way where I can put the code in every document and don't have
to open every document manually and where the code is only available for
these documents and not globally.

My code is very simple. It only displays a messagebox when the document is
opened.

Sub document_open()
MsgBox "Textmessage", vbExclamation
End Sub

Thanks again!
Werner
 
S

Steve Lang

Hi Werner,

Put the code in a template somewhere other than a startup path.
Then run this code on the directory of files. It will attach your template
to the documents so you don't have to manually process them all.

Sub foo()
Dim i As Long
Application.ScreenUpdating = False
With Application.FileSearch
.LookIn = "C:\YourFolder_With_YourFiles"
.SearchSubFolders = True 'if your files may be in subdirs leave as true,
else change to False
.FileName = "*.doc"
.Execute
For i = 1 To .FoundFiles.Count
If InStr(.FoundFiles(i), "~") = 0 Then
'you can change the visible to true if it causes problems.
Documents.Open FileName:=(.FoundFiles(i)), Visible:=False
'Attach your template to the document
ActiveDocument.AttachedTemplate =
"C:\YourTemplatePath\YourTemplate.dot"
'Close document and save changes
ActiveDocument.Close savechanges:=wdSaveChanges
Next i
End With

End Sub
 
K

Klaus Linke

.... and a good reason to put the code in a template instead of in the
documents themselves are the macro warnings you'd get.
Especially if you sometimes send files out of house, the recipient might
have a lot of problems with a doc that contains macros.

And it is easier to change the code in a single template than in 100
documents.

Regards,
Klaus
 
W

Werner Pertl

Hi Steve,

thank you very much for your gr8 help!
This code will save my day!

Werner
 
W

Werner Pertl

Hi Klaus,

yepp, I agree. It's a good idea and I'll try to work more with templates :)

Thanks for your help!

Werner
 

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