|
|
Add-in to merge letters to separate files. |
| |
The macros
at the end of this page were developed from a series of macros produced
by fellow Word
MVP Doug Robbins, who also produced the core macro code for a
method of intercepting Word's built-in 'Merge to a New Document' option,
to merge a form letter merge document directly to individual Word
documents, provided in the form of an add-in for Word. The latest
version of this add-in will be available for download as
a
Word add-in template.
The add-in has undergone many revisions. Please keep an eye on the
What's New page for new releases.
To take advantage of the new features of Word 2007, I
have produced a separate version of the add-in which boasts some
additional features not present in the earlier versions. Where practical
I have added features to the earlier version also. |
| Note 1: |
This add-in is provided in two versions - a dot format template intended to work with Word from version 2002
and 2003, and a dotm format template for Word version 2007. For
earlier Word versions (97 & 2000) the macros included later on this page
should provide an alternative means of splitting merge documents.
Extract the relevant template from the zip file to the Word startup folder, which by
default can be found by typing
%appdata%\Microsoft\Word\STARTUP
in the address bar of
your Windows Explorer application or browser. If you don't have write
access to this folder, ask your IT support to install it for you.
++ Extract ONLY the required template
++ If updating
from an earlier version of
the add-in, remove the older version before starting Word!
++ If
you experience a problem with the add-in, do ensure that you have the
latest version before reporting the problem. The add-in is under regular
development. |
|
Note 2: |
If you use
Word as an editor for Outlook, and with Outlook 2007 where you don't
have the choice, you must start Word before Outlook,
otherwise the autoexec macro in the add-in will not run. Similarly Word
must be started from the Word icon in the Windows start menu, and not by
clicking a document or template in Windows Explorer, for the same
reason. |
|
Note 3: |
The add-in retains information
required for the merge in a
file called Settings.ini which is saved in the user's 'My Documents' folder.
Finding a location that would suit the requirements of all users, which
would work in both the 2003 and 2007 versions, and which would always be
available has proved something of a trial.
The add-in began by using
the root of the C:\ drive, as that tends to be universally available,
but many networked business users reported that their organisations did
not provide write access to this location. Similarly the Word Startup
and Template folders have been tried, but again business users do not
always have write access to these locations.
The Word Documents folder
seemed to fit the bill, but Word 2003 in particular seemed to have
difficulty remembering what that was, resulting in settings files
scattered all over the hard drive. I have therefore settled (until I can
think of something better) on the 'My Documents' folder and I have
introduced a function to identify that wherever it is located. Hopefully
this will please everyone? If not I will probably have to provide a
function to allow the user to select the location of the settings file. |
|
|
The add-ins
are designed to save a letter merge document to separate document files
for each record. They do this by creating a new document for each
record. This works best when the new documents are created from the same
template as the merge document, and included are options to select the
template from which the document was created. If for some reason, that
template is not available, then the functions create documents using the
normal template.
In some
circumstances, this will result in documents that bear only a passing
resemblance to the merge document. To minimise that possibility, the
add-ins also include a macro that will create a template from the merge
document and a copy of that merge document with the new template
attached, which should be used to run the merge in place of the original
merge document. The original merge document is unchanged.
If the
split documents do not appear to match the original merge document
layout, run this macro and then re-run the merge.
In Word
2007 a pair of command buttons is added to the Mailings tab on the ribbon.

In Word
2002/3 this
function is activated from a toolbar button. The toolbar should be
displayed the first time you run Word with the add-in present.
Initially
the toolbar will be displayed in the document space.

If you
don't require the function you can close the toolbar, by clicking the X
on the title bar of the toolbar, and re-activate it as required from
View > Toolbars.

When run,
the macro checks for fatal errors and will produce one of the self
explanatory messages shown below, should such an error be apparent.




If the document's attached template is already
SplitMerge.dot(m) then you will get the following error message and the
application will quit:

If all is well you will see the following dialog:
 |
|
Note: |
The Word
2002/3 version uses similar dialogs with a different background colour. |
| Running the Split Merge function |
| |
The add-in
will intercept the command to merge to a new document and provides
an additional option to merge to separate document files as follows: |
| Word 2002/3 |
| |
Prepare your
merge source document in the usual manner and then click the 'Split the
Merge' button on the template toolbar or 'Merge to
New Document' button on the mail merge toolbar (or select 'Edit
individual letters' from the Mail Merge task pane) |
|

or

|
| Word 2007 |
|

or if following the Step by Step Mail
Merge Wizard


|
| |
Whichever
Word version is employed, you are then
presented with the usual means of choosing which records to merge.
Complete that and click 'OK'

The macro
code then takes over to offer the choice of merging to separate
documents or continuing with a merge to a single document.

If you choose
separate documents, you are offered the list of available fields from
your data file.
The Word 2007
version, additionally offers the user the choice to save the split files
in one from a variety of formats. The Word 2003 version saves the files
in Word Document *.doc format.
If the field contains the path
to the folder in which you wish the files to be saved, check the
checkbox. If not, enter the path in the dialog box where indicated.
 
You may also select the folder to store the merged
documents by clicking the 'Browse' button, which offers the following
dialog.

The add-in
creates a series of new documents. It works best if these new documents
are created using the template from which the merge document was
created. If that template is not available, the new documents are
created using the normal template. You can, if you prefer, use the
normal template to create the documents, by un-checking the check box
shown checked in the illustration above, or run the separate macro from
the toolbar, as detailed earlier on this page, to create a version of
the document c/w attached matching template.
If a record
does not have an entry in the field chosen above or contains a character
that would result in an illegal filename, a warning message is
displayed which shows the content of the record in question and provides
the option to name the document associated with this record or use the
default name NoNameNumber# as shown in the illustrations below.
Note that the illustrations below are from a different data source than
that shown above.



|
|
Note: |
In
addition to a leading full stop (period), the illegal characters that
the macro will not accept are, :- / \ : *
?" < > | |
| |
If you click
'Yes' in the above dialogs, the following screen will take your filename
input.
There is no
need to add .DOC to your choice of filename.

For the
purpose of demonstration I used the following data file, which has a
single field 'Name' with one missing and one duplicated filename.

This produces the following files. Note the results for the duplicated
and missing files.

|
| Merge to Individual PDF
files |
| |
The Word add-in described
above also provides the option to create PDF files.
With Word 2007 if Adobe Acrobat's
Adobe PDF 'printer' driver is available, the merge will only use Acrobat
if the Office 2007 PDF plug-in is not available. The merge to PDF is by
default performed in conjunction with the
Office 2007 PDF plug-in from Microsoft. The
macro detects whether the plug-in is installed by looking for
EXP_PDF.DLL file in the folder %programfiles%\Common
Files\Microsoft Shared\OFFICE12, which is the active part of the
plug in. If it is not installed, the add-in then checks whether the
Acrobat printer driver Adobe PDF is installed, and if available
will print to that. If neither is available a warning message is
presented and the merge is made only to the choice of document format.

Word 2003 version


Even if present other PDF
creation tools are not used. |
|
Note: |
The
Microsoft Office 2007 plug-in is used for preference because it is more
configurable than the Adobe 'printer' driver used by the splitmerge
add-in. The Acrobat versions compatible with Word 2007 do however
provide their own merge function which has greater functionality than is
available from the Adobe PDF 'printer' driver or the Microsoft Office
Plug-in, though not the ability to name the PDF files from the data
source. If you have Acrobat installed, investigate this if you need to
merge to PDF.
The
Acrobat add-in also offers the option to merge PDF to e-mail attachments
which the splitmerge add-in does not include. However see also
Email
Merge With Attachments |
| |
With Word 2002 and 3 this is
performed in conjunction with Acrobat from version 6 (and possibly other PDF
creating tools). In order to do so, the Adobe 'printer' driver called
Adobe PDF must be present in the list of available printers. |
| Note: |
Although
not tested, it may be possible to use other types of PDF creating
'printer' driver with this add-in, provided the 'printer' is renamed
Adobe PDF and it is possible to set the same parameters as listed below.
If anyone tests this with alternative products and finds that it works,
please let me know via the feedback link on
the home page. |
|
|

Before executing
the merge to a new document, select the Adobe PDF printer in the
above list (from Control panel > printers and faxes). Right click and
select Properties and from the dialog box shown below click 'Printing
Preferences'

Uncheck the "View Adobe PDF results" and "Prompt for Adobe PDF filename"
items.
Acrobat 6

Acrobat 7

Acrobat 8

Execute the mailmerge to a
new document and click on "Yes" when you are asked if you want to create
separate files for each document (as in the previous section). Select the field in the datasource
that will supply the filenames and check the box 'Do you want to create
PDF files' in the dialog box shown below

When you click on Continue, as well as having the separate document files saved in the
directory that you had nominated, a .pdf will be created in the My
Documents folder with the name of the .pdf being supplied from the
datasource. If you prefer
to save the PDFs in a different folder you need to create a new 'Port'
for the printer driver and set that as the active port. From Windows
Control panel > Printers and Faxes. Right click the Adobe PDF driver and
select properties from the sub menu.

From the properties menu, select 'Ports'

Then 'Add Port'. The required port type is Adobe PDF Port.

Click New Port and you can choose an output folder for the PDF files.
 |
| Print individual merge letters from a
merged document - doing it the old way. |
|
If you create a merge letter and merge to a
new document without accepting the option to split the merge, you get one long document with each of the individual
'letters' separated by a section break.
It is simple enough to print an individual 'letter' or
range of letters by addressing the sections in the print dialog as in the
illustration below |
|
 |
| Split the single merged document into separate
letters. |
|
Having merged
to a single document, it is still possible to split to
separate documents, with the use of a macro. To this end Doug
Robbins also came up with the following, to which I have taken the
liberty of making a couple of small changes.
The
macro splits the document and files each sub document into the indicated
path - shown here in blue. The files are named by date and sequence
number, with the date format from the mask - also shown in blue. Both
these variables can easily be changed to reflect personal preferences -
nor should it be too difficult for those with vba programming skills and
inclination to modify the code to prompt for a name and/or path.
Sub
Splitter()
' Macro created 16-08-98 by Doug Robbins to save each letter created by a
' mailmerge as a separate file.
' With minor modifications by Graham Mayor 10-02-03
Dim mask As String
Selection.EndKey Unit:=wdStory
Letters = Selection.Information(wdActiveEndSectionNumber)
mask = "ddMMyy"
Selection.HomeKey Unit:=wdStory
Counter = 1
While Counter < Letters
DocName = "D:\My Documents\Temp\Workgroup\"
& Format(Date, mask) _
& " " & LTrim$(Str$(Counter))
& ".doc"
ActiveDocument.Sections.First.Range.Cut
Documents.add
'Documents are based on the Normal template
'To use an alternative template follow the link.
With Selection
.Paste
.EndKey Unit:=wdStory
.MoveLeft Unit:=wdCharacter, Count:=1
.Delete Unit:=wdCharacter, Count:=1
End With
ActiveDocument.SaveAs FileName:=DocName, FileFormat:=wdFormatDocument
ActiveWindow.Close
Counter = Counter + 1
Wend
End Sub
As an alternative, the following macro
provides the opportunity to provide the fixed portion of the filename
and to change the path of the saved files:
Sub SplitMerge()
' Macro created 16-08-98 by Doug Robbins to save each letter created by
a
' mailmerge as a separate file.
' with modifications by Graham Mayor 16-06-03 & 08-10-04
Dim Title As String
Dim Default As String
Dim MyText As String
Dim MyName As Variant
Dim MyPath As String
Selection.EndKey Unit:=wdStory
Letters = Selection.Information(wdActiveEndSectionNumber)
Selection.HomeKey Unit:=wdStory
Counter = 1
Default = "Merged"
MyText = "Enter a filename. Long filenames may be used."
Title = "File Name"
MyName = InputBox(MyText, Title, Default)
If MyName = ""
Then
End
End If
Default = "D:\My Documents\Test\"
Title = "Path"
MyText = "Enter path"
MyPath = InputBox(MyText, Title, Default)
If MyPath = ""
Then
End
End If
While Counter < Letters
Application.ScreenUpdating = False
Docname = MyPath & LTrim$(Str$(Counter)) & " " & MyName
& ".doc"
ActiveDocument.Sections.First.Range.Cut
Documents.Add
'Documents are based on the Normal template
'To use an alternative template follow the link.
With Selection
.Paste
.EndKey Unit:=wdStory
.MoveLeft Unit:=wdCharacter, Count:=1
.Delete Unit:=wdCharacter, Count:=1
End With
ActiveDocument.SaveAs FileName:=Docname, FileFormat:=wdFormatDocument
ActiveWindow.Close
Counter = Counter + 1
Application.ScreenUpdating = True
Wend
End Sub
|
| Note: |
If you
are unsure how to use the above code, see
how to install macros |
| Patience! |
|
Note that as a merge document
may contain hundreds of letters, this macro can take a while to run, as each
document has to be opened and saved, but you should end up with a folder
full of files as shown below (derived from the first code example): |
|
 |
| Naming the file from the data source |
| |
This is
easier said than done, as once the document is merged the data file no
longer forms part of the merge letters. There are a couple of approaches
that may be considered, but the one I favour requires the field to be
used as the filenames to be added to the top of the merge letter on a
line of their own. When merged, the fieldnames will be those first lines
of the merged letters. The macro then removes the lines to restore each
merge letter to its required format during the splitting process.
The only
proviso when choosing filename fields is to choose a combination that
will produce a unique result. If duplicate filenames occur, the macro as
written will simply overwrite the saved file with the new file of the
same name. |
|
 |
| |
The filename
fields above are inserted in red for clarity - the colour applied does
not affect the result. Following the merge (below), the fields are
translated into a 'filename'. |
|
 |
|
|
When the
macro is run, the filename fields are stripped out leaving the merge
letters. |
|
 |
| |
Sub SplitMergeLetter()
' splitter Macro modified to save individual
letters with
' information from
data source. The filename data must be added to
' the top of the merge
letter - see web article.
Selection.EndKey Unit:=wdStory
Letters = Selection.Information(wdActiveEndSectionNumber)
Selection.HomeKey Unit:=wdStory
Counter = 1
While Counter < Letters
Application.ScreenUpdating = False
With Selection
.HomeKey Unit:=wdStory
.EndKey Unit:=wdLine, Extend:=wdExtend
.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
End With
sName = Selection
Docname = "D:\My Documents\Test\Merge\" & sName & ".doc"
ActiveDocument.Sections.First.Range.Cut
Documents.Add
'Documents
are based on the Normal template
'To use an alternative template follow the link.
With Selection
.Paste
.HomeKey Unit:=wdStory
.MoveDown Unit:=wdLine, Count:=1, Extend:=wdExtend
.Delete
End With
ActiveDocument.SaveAs FileName:=Docname, _
FileFormat:=wdFormatDocument
ActiveWindow.Close
Counter = Counter + 1
Application.ScreenUpdating = True
Wend
End Sub |
| Split a merged document to the printer with
each 'letter' treated as a separate print task |
|
|
Where a
merged document consists of several elements e.g. the first page of each
merged letter should be printed on letter headed paper from a different
printer tray, or the printer provides a stapling function for each
'letter', a frequently encountered problem is that the printer loses
track of the tray assignments or in the case of the stapled document,
the whole merge is treated as a single document. To overcome this
problem, fellow MVP Doug Robbins, with whom most of this page has been a
collaborative effort, came up with a macro that treats each letter as a
separate print task.
To use this
macro, merge to a new document then use the macro to print that
document. |
|
|
Sub
SplitMergeLetterToPrinter()
' Macro created 16-08-98 by Doug Robbins to print
each letter created by a
' mailmerge as a separate file.
Letters = ActiveDocument.Sections.Count
counter = 1
While counter < Letters
ActiveDocument.PrintOut Background:=False,
Range:=wdPrintFromTo, _
From:="s" & format(counter), To:="s" & format(counter)
counter = counter + 1
Wend
End Sub |
| Create a
template for the merge splitting macros |
| Note: |
IMPORTANT!! Several of the macros featured on this page create
their new split documents by using the default Normal template as a
basis for the documents. If the merge source document has been
created from a different template, with different margins or page size,
the resulting split documents are not going to match the layout of the
merge document. To overcome this issue, you could create an empty template, by
deleting the content of the merge source document and save it as a
template, then base the split documents on that template. |
|
Note: |
The add-in includes a function to create a template from the document
upon which the following macro is based. |
|
|
The
following macro will create a template from the merged document called
splitmerge.dot(x) which it will store in the default user template
location.
To use the
splitmerge.dot(x) template in the examples above, locate the line
Documents.Add
and replace
it with
If
Application.Version < 12 Then
Documents.Add Options.DefaultFilePath(Path:=wdUserTemplatesPath)
& "\splitmerge.dot"
Else
Documents.Add Options.DefaultFilePath(Path:=wdUserTemplatesPath)
& "\splitmerge.dotx"
End If |
|
|
Sub
CreateSplitMergeTemplate()
Dim sTempPath As
String
Dim sQuery As String
Dim sRestore As
String
Dim sATemp As String
Dim oSection As
Section
Dim oStory As
Range
Dim oMergeDoc As
Document
If Documents.Count = 0
Then
MsgBox "No document present!" & vbCr & _
"Open the merged document and run this macro again", _
vbCritical, "Merge Template Creator"
Exit Sub
End If
Set oMergeDoc = ActiveDocument
If InStr(1, oMergeDoc, ".dot")
Then
MsgBox "Active document is a template!" & vbCr & _
"Open the merged document and run this macro again", _
vbCritical, "Merge Template Creator"
Exit Sub
End If
sTempPath = Options.DefaultFilePath(Path:=wdUserTemplatesPath) & Chr(92)
With oMergeDoc
If
Application.Version = 12 Then
.SaveAs FileName:="SplitMerge.docx",
_
FileFormat:=wdFormatXMLDocument
Else
.SaveAs FileName:="SplitMerge.doc",
_
FileFormat:=wdFormatDocument
End If
sRestore = .FullName
For Each
oSection In .Sections
oSection.Range.Delete
Next oSection
For
Each oStory In .StoryRanges
oStory.Delete
If oStory.StoryType <> wdMainTextStory Then
While Not (oStory.NextStoryRange Is Nothing)
Set oStory = oStory.NextStoryRange
oStory.Delete
Wend
End If
Next oStory
Set oStory =
Nothing
With .PageSetup
.OddAndEvenPagesHeaderFooter
= False
.DifferentFirstPageHeaderFooter
= False
End With
If Application.Version = 12
Then
.SaveAs FileName:=sTempPath
& "SplitMerge.dotx", _
FileFormat:=wdFormatXMLTemplate
Else
.SaveAs FileName:=sTempPath
& "SplitMerge.dot", _
FileFormat:=wdFormatTemplate
End If
sATemp = .FullName
.Close SaveChanges:=wdDoNotSaveChanges
End With
Documents.Open sRestore
With ActiveDocument
.AttachedTemplate = sATemp
.Save
End With
End Sub |