Skip to main content

Microsoft VBA Script to save mail merged word documents into separate files

' First add the mail merged fields and save the document

'Then reopen the word document and click no to SQL import and open VBA editor and paste this script

'Finally save this as a macro enabled document and test this code

'Happy coding




Option Explicit


Dim FOLDER_SAVED As String

Dim SOURCE_FILE_PATH As String







Function ReplaceIllegalCharacters(strIn As String, strChar As String) As String

    Dim strSpecialChars As String

    Dim i As Long

    strSpecialChars = "~""#%&*:<>?{|}/\[]" & Chr(10) & Chr(13)


    For i = 1 To Len(strSpecialChars)

        strIn = Replace(strIn, Mid$(strSpecialChars, i, 1), strChar)

    Next


    ReplaceIllegalCharacters = strIn

End Function


Sub TestRun()

Dim MainDoc As Document, TargetDoc As Document

Dim dbPath As String, FileName As String, Folder As String

Dim recordNumber As Long, totalRecord As Long, startingRec As Integer, endingIndex As Integer

Dim Answer As VbMsgBoxResult



Set MainDoc = ActiveDocument



FOLDER_SAVED = "C:\temp\new\"

SOURCE_FILE_PATH = "C:\temp\Content-Planning-EN-Dev.xlsx"


      startingRec = 1

      Dim userdata As Variant, userdata2 As Variant, userdata3 As Variant, userdata4 As Variant








With MainDoc.MailMerge






        

        

        

        

        

        userdata3 = InputBox("Please enter the source file path", "Destination folder", "C:\temp\Content-Planning-EN-Dev.xlsx")

        

        FileName = VBA.FileSystem.Dir(userdata3)

        

        If FileName = "" Then

        MsgBox "File does not exist."

        Else

        SOURCE_FILE_PATH = userdata3

        End If

        


        

        userdata4 = InputBox("Please enter the destination folder", "Destination folder", "C:\temp\new\")

        

        Folder = Dir(userdata4, vbDirectory)


        

         If Folder = "" Then

        Answer = MsgBox("Path does not exist. Would you like to create it?", vbYesNo, "Create Path?")


        Select Case Answer

                Case vbYes

                    VBA.FileSystem.MkDir (userdata4)

                Case Else

                    Exit Sub

        End Select

    

        Else

    

            'MsgBox "Folder exists."

            FOLDER_SAVED = userdata4

    

        End If



        '// if you want to specify your data, insert a WHERE clause in the SQL statement

        .OpenDataSource Name:=SOURCE_FILE_PATH, sqlstatement:="SELECT * FROM [Briefings$]"

            

        totalRecord = .DataSource.RecordCount




    


        

        



        userdata = InputBox("Please enter starting Index", "starting Index", 1)

        If IsNumeric(userdata) Then

        startingRec = userdata

        Else

        MsgBox "Not a Number"

        Exit Sub

        End If

        

        

        userdata2 = InputBox("Please enter Ending Index", "Ending Index", totalRecord)

        If IsNumeric(userdata2) Then

        

            endingIndex = userdata2

            

            If (endingIndex > totalRecord Or endingIndex < 1) Then

            MsgBox "Out of range"

            Exit Sub

             

            Else

            totalRecord = endingIndex

            

            

            End If

        

          

        End If

        

        

        

        

        

        

        

        

        

        

        '.DataSource.DataFields("Topic").Value

        

        


        For recordNumber = startingRec To totalRecord

        

            With .DataSource

                .ActiveRecord = recordNumber

                .FirstRecord = recordNumber

                .LastRecord = recordNumber

            End With

            

            .Destination = wdSendToNewDocument

            .Execute False

            

            Set TargetDoc = ActiveDocument

            Word.Options.AutoFormatReplaceHyperlinks = True

            TargetDoc.Range.AutoFormat


            TargetDoc.SaveAs2 FOLDER_SAVED & ReplaceIllegalCharacters(.DataSource.DataFields("Topic").Value, "_") & ".docx", wdFormatDocumentDefault

            'TargetDoc.ExportAsFixedFormat FOLDER_SAVED & .DataSource.DataFields("Client_Name").Value & ".pdf", exportformat:=wdExportFormatPDF

            

            TargetDoc.Close False

            

            Set TargetDoc = Nothing

                    

        Next recordNumber


End With


Set MainDoc = Nothing

End Sub


Comments

Popular posts from this blog

Murach's JavaScript and DOM Scripting

by Ray Harris 20 chapters, 764 pages, 337 illustrations ISBN: 978-1-890774-55-4 Today, web users expect web sites to provide advanced features, dynamic user interfaces, and fast response times. To deliver that, you need to know the JavaScript language. Beyond that, though, you need to know how to use JavaScript to script the Document Object Model (or DOM). Now, at last, you can learn both JavaScript and DOM scripting in this one great book. In fact, by the end of chapter 3, you'll be able to develop and debug significant JavaScript applications. By the end of section 2, you'll know the complete JavaScript language and some elementary DOM scripting. And by end of section 3, you will have raised your DOM scripting skills to an expert level.

Murach's Java SE 6

Murach's Java SE 6 by Joel Murach and Andrea Steelman 22 chapters, 810 pages, 351 illustrations ISBN-10: 1-890774-42-1; ISBN-13: 978-1-890774-42-4 "I love your Java book. It cuts right to the essential information, providing the perfect balance between too many details and too little information. I bought another well-known Java book, but I spent several hours trying to learn what I learned from your book in about 45 minutes." That's what one developer wrote us about the JDK 5 edition of our core Java book. Now, you can expect that same practical, time-saving approach in the current edition that covers the latest version of Java, Java SE 6. What you'll learn from the SE 6 edit...

Murach's Java Servlets and JSP (2nd Edition)

by Joel Murach and Andrea Steelman    24 chapters, 729 pages, 329 illustrations ISBN-13: 978-1-890774-44-8 Ever since we published the first edition of this book back in 2003, we've been getting feedback like this from developers: "This book is excellent, excellent, excellent! The authors have a gift for developing the topic of JSP, Servlets, and building a Java-based ecommerce site in a methodical, easy-to-understand approach." Now, I'm delighted to tell you that you'll feel the same way about this new, 2nd edition. The content has been redone from start to finish, so you'll learn the best features, tools, and techniques for developing today's web applications (see what's NEW below).But our popular approach hasn't changed: This 2nd edition still presents Java web programming ...