12

I have an excel sheet with data and want to export it to a new word document.

Is it possible to start MAIL MERGE from excel macro by clicking a button on the sheet?

Teamothy
  • 2,000
  • 3
  • 16
  • 26
Tom
  • 6,725
  • 24
  • 95
  • 159

5 Answers5

21

If your Word document is already configured with the merge fields, and you are running the macro from the workbook that contains the data you want to merge into the Word document, then try this:

Sub RunMerge()

    Dim wd As Object
    Dim wdocSource As Object

    Dim strWorkbookName As String

    On Error Resume Next
    Set wd = GetObject(, "Word.Application")
    If wd Is Nothing Then
        Set wd = CreateObject("Word.Application")
    End If
    On Error GoTo 0

    Set wdocSource = wd.Documents.Open("c:\test\WordMerge.docx")

    strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name

    wdocSource.MailMerge.MainDocumentType = wdFormLetters

    wdocSource.MailMerge.OpenDataSource _
            Name:=strWorkbookName, _
            AddToRecentFiles:=False, _
            Revert:=False, _
            Format:=wdOpenFormatAuto, _
            Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
            SQLStatement:="SELECT * FROM `Sheet1$`"

    With wdocSource.MailMerge
        .Destination = wdSendToNewDocument
        .SuppressBlankLines = True
        With .DataSource
            .FirstRecord = wdDefaultFirstRecord
            .LastRecord = wdDefaultLastRecord
        End With
        .Execute Pause:=False
    End With

    wd.Visible = True
    wdocSource.Close SaveChanges:=False

    Set wdocSource = Nothing
    Set wd = Nothing

End Sub
dendarii
  • 2,958
  • 20
  • 15
6

To get dendarii's solution to work I had to declare Word constants in Excel VBA as follows:

' Word constants
Const wdFormLetters = 0, wdOpenFormatAuto = 0
Const wdSendToNewDocument = 0, wdDefaultFirstRecord = 1, wdDefaultLastRecord = -16
MattM
  • 61
  • 1
  • 2
  • Good point, MattM. If you don't have a reference set in Excel VBA to the Word object (in the VBA Editor, Tools > References > Microsoft Word [version] Object Library), the Word constants will not work, and you will have to use MattM's values instead. – dendarii Feb 27 '13 at 09:53
1

If your word document is already configured with data source and merge fields layout then it becomes much simpler. In the example below MailMergeLayout.doc is all setup ready to perform a merge. A button in Excel is linked to RunMailMerge() as below. All the code is contained in an Excel VBA module.

Sub RunMailMerge()

    Dim wdOutputName, wdInputName As String
    wdOutputName = ThisWorkbook.Path & "\Reminder Letters " & Format(Date, "d mmm yyyy")
    wdInputName = ThisWorkbook.Path & "\MailMergeLayout.doc"

    ' open the mail merge layout file
    Dim wdDoc As Object
    Set wdDoc = GetObject(wdInputName, "Word.document")
    wdDoc.Application.Visible = True

    With wdDoc.MailMerge
         .MainDocumentType = wdFormLetters
         .Destination = wdSendToNewDocument
         .SuppressBlankLines = True
         .Execute Pause:=False
    End With

    ' show and save output file
    wdDoc.Application.Visible = True
    wdDoc.Application.ActiveDocument.SaveAs wdOutputName

    ' cleanup
    wdDoc.Close SaveChanges:=False
    Set wdDoc = Nothing

End Sub
Robert
  • 11
  • 1
0
Private Sub CommandButton1_Click()

 Set wordapp = CreateObject("word.Application")

     wordapp.documents.Open "C:\Documents and Settings\User\Desktop\mergeletter.doc"


    wordapp.Visible = True

    wrddoc = wordapp.documents("C:\Users\User\Desktop\sourceofletters.xls")


   wrddoc.mailmerge.maindocumenttype = wdformletters

   With wrddoc.activedocument.mailmerge

 .OpenDataSource Name:="C:\Users\User\Desktop\sourceofletters.xls", _
           SQLStatement:="SELECT * FROM `Sheet1`"



   End With

End Sub

Above code is to open a word mailmerge document (with its source link and mergefield codes all setup ) all I want is for the message box "Opening the document will run the following SQL command " to be made available to the user , from that point forward the user could either select 'Yes' or 'No'.

SalvadorVayshun
  • 343
  • 1
  • 3
  • 19
cyrus
  • 11
  • 1
-3
Dim opt As String
opt = MessageBox("Opening the document will run the following SQL command", vbYesNo)
If opt = vbYes Then
   'execute query
End If