Word 2007/2010 Mail Merge to save to individual PDF files

kryptonian

Board Regular
Joined
Oct 6, 2006
Messages
104
I tried using gmayor's Individual Merge Letters solution but my file only closes without doing anything so I am posting here as a last recourse...

Here's what I want to do --

I'm using Word 2007/2010 mail merge and I want to create individual PDF files. Currently, we do it the long way, saving it one PDF at a time using Save As. This works if it only a handful of letters but it becomes a pain when we're processing hundreds! Data source is an Excel file.

Any help would be greatly appreciated!
 
This gives me a runtime error '5941' The requested member of the collection does not exist. The debug highlights:

StrName = strFolder & Trim(.DataFields("Name")) & "-" & Format(.DataFields("Date"), "YYYY_MM_DD")

Does it matter that I'm using word 2003? I did also make sure ms forms 2.0 object library is checked.
 
Last edited by a moderator:
Upvote 0

Excel Facts

Round to nearest half hour?
Use =MROUND(A2,"0:30") to round to nearest half hour. Use =CEILING(A2,"0:30") to round to next half hour.
The error is because your data source does not have fields named 'Name' and/or 'Date', per your previous advice:
'name' and 'date' being data pulled from the mail merge
You'll have to modify the code to match whatever your field names are.
 
Upvote 0
Dear all

Thank you Cindy Ellis and kryptonian!!

Thank you so much for this thread, based on your code I have been able to successfully perform email merge and send with a unique attachment for each message. (Previously staff have been creating and emailing documents one by one...!!)

However while the macro works fine on the independent office laptop running Windows 8, it does not work on the networked desktop PC running Windows 7 Enterprise SP1 (64 bit), with Word and Outlook v. 14.0.7117.5001 (32 bit). The macro seems to run as normal but at the end it says "0 messages sent" and indeed no messages are sent. There are no error messages. I have tried changing the security settings in Outlook but to no avail.

There is also another PC running XP SP3 with Word 2003 v.11.8411.8405 and Outlook 2003 v.11.8339.8405 (don't laugh!) - I can also use this PC which is not networked, in case network settings are the problem. Running the macro on this system produces the same result - no error messages, outcome of "0 messages sent".

I'm mystified by the lack of error messages and the "0 messages sent" outcome.

This is a real pain since the laptop belongs to my boss and she takes it away frequently on meetings - not much use when there is a lot of processing to be done.

What changes do I need to make to persuade the macro to run on the desktop PC?

Many thanks
Keren

Code based on the initial posts in this thread:
Code:
Sub Email_merge_with_attachments()
    Dim Source As Document, Maillist As Document, TempDoc As Document
    Dim Datarange As Range
    Dim i As Long, j As Long
    Dim bStarted As Boolean
    Dim oOutlookApp As Outlook.Application
    Dim oItem As Outlook.MailItem
    Dim mysubject As String, message As String, title As String
    Set Source = ActiveDocument
    ' Check if Outlook is running.  If it is not, start Outlook
    On Error Resume Next
    Set oOutlookApp = GetObject(, "Outlook.Application")
    If Err <> 0 Then
    Set oOutlookApp = CreateObject("Outlook.Application")
    bStarted = True
End If
' Open the catalog mailmerge document
With Dialogs(wdDialogFileOpen)
    .Show
End With
    Set Maillist = ActiveDocument
    'Could change this to automatically set email subject
    ' Show an input box asking the user for the subject to be inserted into the email messages
    message = "Enter the subject to be used for each email message."    ' Set prompt.
    title = " Email Subject Input"    ' Set title.
    ' Display message, title
    mysubject = InputBox(message, title)
    ' Iterate through the Sections of the source Excel document and the rows of the directory mailmerge document,
    ' extracting the information to be included in each email.
For j = 1 To Source.Sections.Count - 1
    Set oItem = oOutlookApp.CreateItem(olMailItem)
    With oItem
        .Subject = mysubject
        .Body = Source.Sections(j).Range.Text
        Set Datarange = Maillist.Tables(1).Cell(j, 1).Range
        Datarange.End = Datarange.End - 1
        .To = Datarange
        For i = 2 To Maillist.Tables(1).Columns.Count
            Set Datarange = Maillist.Tables(1).Cell(j, i).Range
            Datarange.End = Datarange.End - 1
            .Attachments.Add Trim(Datarange.Text), olByValue, 1
        Next i
        .Send
    End With
    Set oItem = Nothing
Next j
Maillist.Close wdDoNotSaveChanges
'  Close Outlook if it was started by this macro.
If bStarted Then
    oOutlookApp.Quit
End If
MsgBox Source.Sections.Count - 1 & " messages have been sent."
'Clean up
Set oOutlookApp = Nothing
End Sub
 
Last edited by a moderator:
Upvote 0
Hi Cindy,
This line is yellow:
Code:
docname = .DataFields("ASP_Print").Value & ".docx"      ' ADDED CODE
How do I debug this?
 
Upvote 0
Dear all

Thank you Cindy Ellis and kryptonian!!

Thank you so much for this thread, based on your code I have been able to successfully perform email merge and send with a unique attachment for each message. (Previously staff have been creating and emailing documents one by one...!!)

I would also like to pass along a huge thanks to both kryptonian and Cindy Ellis. I have absolutely zero knowledge of VB, however using the posted code I have been able to generate unique PDFs for each record in my source (an Access Query) saved to a folder chosen when macro first runs, with a unique filename which is taken from a field in the data source.

Like kilogranules I am trying to use this macro to email the result. What I would really like to do is to be able to email the saved PDF as an attachment with the email address «contactemail», and email subject "Here is your attachment «batch»" taken from the data source and include a static text body in the email: "Hi, here is the document you requested"

The code I am using to generate and save PDF for each record is as follows:

Code:
 Public Sub CreatePDF()
 '
 ' CreatePDF Macro
 '
 '
 ' From: [URL]http://www.mrexcel.com/forum/general-excel-discussion-other-questions/713478-word-2007-2010-mail-merge-save-individual-pdf-files.html[/URL]
  
     Dim fd As FileDialog
 
    'Create a FileDialog object as a Folder Picker dialog box.
     Set fd = Application.FileDialog(msoFileDialogFolderPicker)
     With fd
 
        'Use the Show method to display the Folder Picker dialog box and return the user's action.
         'The user pressed the button.
         If .Show = -1 Then
                 For Each vrtSelectedItem In .SelectedItems
 
                'vrtSelectedItem is aString that contains the path of each selected item.
                 'You can use any file I/O functions that you want to work with this path.
                 'This example displays the path in a message box.
         SelectedPath = vrtSelectedItem
 
        Next vrtSelectedItem
 
        Else
         MsgBox ("No Directory Selected.  Exiting")
         Exit Sub
         End If
     End With
 
    'Set the object variable to Nothing.
     Set fd = Nothing
 
            
 Application.ScreenUpdating = False
 
ThisDoc = ActiveDocument.Name
     ChangeFileOpenDirectory SelectedPath
     For i = 1 To ActiveDocument.MailMerge.DataSource.RecordCount
         With ActiveDocument.MailMerge
             .Destination = wdSendToNewDocument
             .SuppressBlankLines = True
 ' MsgBox "Press OK"
             With .DataSource
                 .FirstRecord = i
                 .LastRecord = i
                 .ActiveRecord = i
                 docname = .DataFields("Batch").Value & ".pdf"
             End With
             .Execute Pause:=False
     Application.ScreenUpdating = True
     
             
         End With
         ActiveDocument.ExportAsFixedFormat OutputFileName:=docname, _
         ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
         wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, To:=1, _
         Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
         CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
         BitmapMissingFonts:=True, UseISO19005_1:=False
         ActiveWindow.Close False
 '    Windows(ThisDoc).Activate
     Next i
 Application.ScreenUpdating = True
 End Sub

I would be extremely appreciative if someone could show me how to acheive the next big step in automating the painfully repetitive task of emailing the unique PDF attachments out.

Thanks
 
Upvote 0
Cindy and Macropod,

Thank you (albeit a late one) for the original macro to merge into PDF. I have been successfully using it for the last 18 months without a problem.

However, I ran into a new situation today, the file I usually output has evolved into two pages now and the macro somehow doesn't output the fields in the second page. I still get two pages in the output file, but the second page doesn't show up any of the fields. I am sure this needs a small tweak, but I'm unable to find out what.

Please help!
Code:
Sub merge1record_at_a_time() '
' merge1record_at_a_time Macro
'
'
    Dim fd As FileDialog




    'Create a FileDialog object as a Folder Picker dialog box.
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    With fd




        'Use the Show method to display the Folder Picker dialog box and return the user's action.
        'The user pressed the button.
        If .Show = -1 Then
                For Each vrtSelectedItem In .SelectedItems




                'vrtSelectedItem is aString that contains the path of each selected item.
                'You can use any file I/O functions that you want to work with this path.
                'This example displays the path in a message box.
        SelectedPath = vrtSelectedItem




        Next vrtSelectedItem




        Else
        MsgBox ("No Directory Selected.  Exiting")
        Exit Sub
        End If
    End With




    'Set the object variable to Nothing.
    Set fd = Nothing




Application.ScreenUpdating = False




MainDoc = ActiveDocument.Name
    ChangeFileOpenDirectory SelectedPath
    For i = 1 To ActiveDocument.MailMerge.DataSource.RecordCount
        With ActiveDocument.MailMerge
            .Destination = wdSendToNewDocument
            .SuppressBlankLines = True
            With .DataSource
                .FirstRecord = i
                .LastRecord = i
                .ActiveRecord = i
                docName = .DataFields("Roll_no").Value & ".PDF"      ' ADDED CODE
            End With
            .Execute Pause:=False
    Application.ScreenUpdating = False
            
        End With
    ActiveDocument.ExportAsFixedFormat OutputFileName:=docName, _
        ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
        wdExportOptimizeForPrint, Range:=wdExportAllDocument, From:=1, to:=1, _
        Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
        CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
        BitmapMissingFonts:=True, UseISO19005_1:=False
ActiveWindow.Close SaveChanges:=False


    
    Next i
Application.ScreenUpdating = True




End Sub
 
Last edited by a moderator:
Upvote 0
Cindy and Macropod,

Thank you (albeit a late one) for the original macro to merge into PDF. I have been successfully using it for the last 18 months without a problem.

However, I ran into a new situation today, the file I usually output has evolved into two pages now and the macro somehow doesn't output the fields in the second page. I still get two pages in the output file, but the second page doesn't show up any of the fields. I am sure this needs a small tweak, but I'm unable to find out what.

Please help!
[/code]

I figured out what the problem was, turns out it had nothing to do with the macro. My file has background images on both pages and the one on the second page somehow got in front of the mergefields. Rearranged it and now everything is perfect! Thank you once again everyone, this is a great site!
 
Upvote 0
WoW! Thanx guys thats amaizing! I've been trying to figure this out for a year!
The macro works perfectly
 
Last edited:
Upvote 0
Hi.

Is there anyway to add this solution with a specific password protection for each document printed in PDF from mail merge ?
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,337
Members
452,637
Latest member
Ezio2866

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top