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

Download Facebook or Youtube Videos Without Any Tools

                Have you ever liked a video shared by your friend on facebook and wanted to download it…Well this this tutorial is not only for facebook or youtube instead it can be used for any video streaming website like metacafe,dailymotion,veoh or yahoo videos.There are websites on the internet that will convert your video link into a download link but it has the following drawback

How To Remove “Error Deleting File or Folder”

It is a very common and annoying message that the file or folder you are trying to deleted cannot be deleted or thependrive cannot be removed as it is used by the system.In this tutorial I will show how to remove your pendrive or delete the files and folders if you get such an error.This error has various flavours and it can be of any of the following types:

What is the term Multiplexing in data transmission ?

  Multiplexing is the technique of combining multiple signals into a single signal for transmission over a communication channel. In data transmission, multiplexing allows multiple users to share a single communication channel, maximizing its use and increasing efficiency. There are several types of multiplexing used in data transmission, including: Frequency Division Multiplexing (FDM): This technique divides the available frequency range into multiple non-overlapping sub-channels, each of which can be used by a separate signal. Each signal is modulated onto a separate carrier frequency and combined into a single composite signal for transmission. FDM is commonly used in analog systems, such as radio and television broadcasting. Time Division Multiplexing (TDM): This technique divides the available time into multiple time slots, with each slot dedicated to a separate signal. Each signal is transmitted in its designated time slot, and the signals are interleaved in time to create a com