View Single Post
Old 10-04-2019, 09:37 AM is offline Windows 10 Office 2016
Join Date: Oct 2019
Posts: 4 is on a distinguished road
Default Separate mail merge into individual documents

Hi Paul -

Thanks for replying. I have the following code from the internet. Can you check it to see if there is something wrong with the changes I made to it?

Also, I put it under the VBA code where it says (General) on the left-hand side at the top and the right-hand drop down is Merge_To_Individual_Files. Is that right?

I tried running it by pressing F5 and it just sits there.

Sub Merge_To_Individual_Files()
' Sourced from:
Application.ScreenUpdating = False
Dim StrFolder As String, StrName As String, MainDoc As Document, i As Long, j As Long
Const StrNoChr As String = """*./\:?|"
Set MainDoc = ActiveDocument
With MainDoc
  StrFolder = .Path & Application.PathSeparator
  For i = 1 To .MailMerge.DataSource.RecordCount
    With .MailMerge
      .Destination = wdSendToNewDocument
      .SuppressBlankLines = True
      With .DataSource
        .FirstRecord = i
        .LastRecord = i
        .ActiveRecord = i
        If Trim(.DataFields("Report_Name")) = "" Then Exit For
        'StrFolder = .DataFields("Folder") & Application.PathSeparator

        StrName = .DataFields("Report_Name")
            '& "_" & .DataFields("First_Name")
      End With
      .Execute Pause:=False
      If Err.Number = 5631 Then
        GoTo NextRecord
      End If
    End With
      For j = 1 To Len(StrNoChr)
        StrName = Replace(StrName, Mid(StrNoChr, j, 1), "_")
    StrName = Trim(StrName)
    With ActiveDocument
      'Add the name to the footer
      '.Sections(1).Footers(wdHeaderFooterPrimary).Range.InsertBefore StrName
      .SaveAs FileName:=StrFolder & StrName & ".docx", FileFormat:=wdFormatXMLDocument, AddToRecentFiles:=False

      ' and/or:
      '.SaveAs FileName:=StrFolder & StrName & ".pdf", FileFormat:=wdFormatPDF, AddToRecentFiles:=False
      '.Close SaveChanges:=False
    End With
  Next i
End With

Application.ScreenUpdating = True
End Sub
Any help will be appreciated!
Reply With Quote