Visual Basic Development Bookmark and Share   
 Home > Visual Basic General > Mail Merge using DataGridView as DataSource
 

Mail Merge using DataGridView as DataSource

Hello,

I'm trying to use a datagridview as the datasource for my mail merge, but I'm having trouble getting all the data to output to the word doc. I've based the below code on the following tutorial:

http://support.microsoft.com/kb/301656/en-us

and I've modified the code accordingly.

Private Sub btnMailMerge_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMailMerge.Click
        Dim wrdSelection As Word.Selection
        Dim wrdMailMerge As Word.MailMerge
        Dim wrdMergeFields As Word.MailMergeFields
        Dim selectedRowCount As Integer = DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)

        Dim StrToAdd As String

        ' Create an instance of Word  and make it visible.
        wrdApp = CreateObject("Word.Application")
        wrdApp.Visible = True

        ' Add a new document.
        wrdDoc = wrdApp.Documents.Add()
        wrdDoc.Select()

        wrdSelection = wrdApp.Selection()
        wrdMailMerge = wrdDoc.MailMerge()

        ' Create MailMerge Data file.
        'CreateMailMergeDataFile()
        wrdDoc.MailMerge.CreateDataSource(Name:=DataGridView1.Item(0, 1).Value, _
             HeaderRecord:="FirstName, LastName, Address1, Address2, Address3, Address4")

        ' Create a string and insert it in the document.
        StrToAdd = "International Academy of Computer Training" & vbCr & _
                    "VB.NET Level 1 Project"
        wrdSelection.ParagraphFormat.Alignment = _
                    Word.WdParagraphAlignment.wdAlignParagraphCenter
        wrdSelection.TypeText(StrToAdd)

        InsertLines(4)

        ' Insert merge data.
        wrdSelection.ParagraphFormat.Alignment = _
                    Word.WdParagraphAlignment.wdAlignParagraphLeft
        wrdMergeFields = wrdMailMerge.Fields()
        'wrdMergeFields.Add(wrdSelection.Range, "FirstName")
        wrdMergeFields.Add(wrdSelection.Range, DataGridView1.Item(0, 1).Value)
        wrdSelection.TypeText(" ")
        'wrdMergeFields.Add(wrdSelection.Range, "LastName")
        wrdMergeFields.Add(wrdSelection.Range, DataGridView1.Item(1, 1).Value)
        wrdSelection.TypeParagraph()

        'wrdMergeFields.Add(wrdSelection.Range, "Address1")
        wrdMergeFields.Add(wrdSelection.Range, DataGridView1.Item(2, 1).Value)
        wrdSelection.TypeParagraph()
        'wrdMergeFields.Add(wrdSelection.Range, "Address2")
        wrdMergeFields.Add(wrdSelection.Range, DataGridView1.Item(3, 1).Value)
        wrdSelection.TypeParagraph()
        'wrdMergeFields.Add(wrdSelection.Range, "Address3")
        wrdMergeFields.Add(wrdSelection.Range, DataGridView1.Item(4, 1).Value)
        wrdSelection.TypeParagraph()
        'wrdMergeFields.Add(wrdSelection.Range, "Address4")
        wrdMergeFields.Add(wrdSelection.Range, DataGridView1.Item(5, 1).Value)

        InsertLines(2)

        ' Right justify the line and insert a date field
        ' with the current date.
        wrdSelection.ParagraphFormat.Alignment = _
               Word.WdParagraphAlignment.wdAlignParagraphRight
        wrdSelection.InsertDateTime( _
              DateTimeFormat:="dddd, MMMM dd, yyyy", _
              InsertAsField:=False)

        InsertLines(2)

        ' Justify the rest of the document.
        wrdSelection.ParagraphFormat.Alignment = _
               Word.WdParagraphAlignment.wdAlignParagraphJustify

        wrdSelection.TypeText("Dear ")
        wrdMergeFields.Add(wrdSelection.Range, DataGridView1.Item(0, 1).Value)
        wrdSelection.TypeText(",")
        InsertLines(2)

        ' Create a string and insert it into the document.
        StrToAdd = "Thank you for attending the recent VB.NET course " & _
            "at IACT, we are delighted to inform you that you have " & _
            "passed with flying colours. Thank you for attending our " & _
            "and we wish you all the best for the future."
        wrdSelection.TypeText(StrToAdd)

        InsertLines(2)

        ' Create a string and insert it into the document.
        StrToAdd = "For information on additional courses, please visit " & _
                   "our website at "
        wrdSelection.TypeText(StrToAdd)
        ' Insert a hyperlink to the Web page.
        wrdSelection.Hyperlinks.Add(Anchor:=wrdSelection.Range, _
           Address:="http://www.iact.ie")
        ' Create a string and insert it in the document.
        StrToAdd = ". Thank you for your interest in the classes " & _
                   "offered, we look forward to hearing from you in the " & _
                   "again. " & vbCr & vbCr & _
                   "Sincerely," & vbCr & vbCr & vbCr & _
                   "Joe Bloggs" & vbCr & _
                   "Director IACT" & vbCr
        wrdSelection.TypeText(StrToAdd)

        ' Perform mail merge.
        wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument
        'wrdMailMerge.Execute(False)
        wrdMailMerge.Execute(True)

        ' Close the original form document.
        wrdDoc.Saved = True
        wrdDoc.Close(False)

        ' Release References.
        wrdSelection = Nothing
        wrdMailMerge = Nothing
        wrdMergeFields = Nothing
        wrdDoc = Nothing
        wrdApp = Nothing

        ' Clean up temp file.
        'System.IO.File.Delete("C:\DataDoc.doc")
    End Sub
Any help on getting this working would be much appreciated, I feel its nearly working and just needs to be tweeked slightly.

Regards.....
6foot7  Monday, November 30, 2009 5:10 PM
Why a DataGridView as Datasource.

A DataGridView datasource is simply a property to connect the databinding to a table.

Take the original table or generic list that is binded to your DataGridView.


Success
Cor
Cor Ligthert  Monday, November 30, 2009 5:57 PM
I'll give that a go Cor, can't do it today, but I'll get back to you tomorrow and let you know how it goes.
6foot7  Monday, November 30, 2009 6:25 PM
Cor,

I'm having trouble opening the database, I've changed the code to:
Private Sub btnMailMerge_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMailMerge.Click
        Dim wrdSelection As Word.Selection
        Dim wrdMailMerge As Word.MailMerge
        Dim wrdMergeFields As Word.MailMergeFields

        Dim StrToAdd As String

        ' Create an instance of Word and make it visible (i.e opens up MicroSoft Word).
        wrdApp = CreateObject("Word.Application")
        wrdApp.Visible = True

        ' Adds a blank document called "Document1".
        wrdDoc = wrdApp.Documents.Add()
        wrdDoc.Select()

        wrdSelection = wrdApp.Selection()
        wrdMailMerge = wrdDoc.MailMerge()

        ' Create MailMerge Data file.
        wrdDoc.MailMerge.OpenDataSource(Name:="G:\VB Level 1\Project\ContactsDB.mdf", _
            SQLStatement:="Select FirstName, LastName, Address1, Address2, Address3, Address4 from [Contacts]")

        ' Create a string and insert it in the document.
        StrToAdd = "International Academy of Computer Training" & vbCr & _
                    "VB.NET Level 1 Project"
        wrdSelection.ParagraphFormat.Alignment = _
                    Word.WdParagraphAlignment.wdAlignParagraphCenter
        wrdSelection.TypeText(StrToAdd)

        InsertLines(4)

        ' Insert merge data.
        wrdSelection.ParagraphFormat.Alignment = _
                    Word.WdParagraphAlignment.wdAlignParagraphLeft
        wrdMergeFields = wrdMailMerge.Fields()
        wrdMergeFields.Add(wrdSelection.Range, "FirstName")
        wrdSelection.TypeText(" ")
        wrdMergeFields.Add(wrdSelection.Range, "LastName")
        wrdSelection.TypeParagraph()

        wrdMergeFields.Add(wrdSelection.Range, "Address1")
        wrdSelection.TypeParagraph()
        wrdMergeFields.Add(wrdSelection.Range, "Address2")
        wrdSelection.TypeParagraph()
        wrdMergeFields.Add(wrdSelection.Range, "Address3")
        wrdSelection.TypeParagraph()
        wrdMergeFields.Add(wrdSelection.Range, "Address4")

        InsertLines(2)

        ' Right justify the line and insert a date field
        ' with the current date.
        wrdSelection.ParagraphFormat.Alignment = _
               Word.WdParagraphAlignment.wdAlignParagraphRight
        wrdSelection.InsertDateTime( _
              DateTimeFormat:="dddd, MMMM dd, yyyy", _
              InsertAsField:=False)

        InsertLines(2)

        ' Justify the rest of the document.
        wrdSelection.ParagraphFormat.Alignment = _
               Word.WdParagraphAlignment.wdAlignParagraphJustify

        wrdSelection.TypeText("Dear ")
        wrdMergeFields.Add(wrdSelection.Range, DataGridView1.Item(0, 1).Value)
        wrdSelection.TypeText(",")
        InsertLines(2)

        ' Create a string and insert it into the document.
        StrToAdd = "Thank you for attending the recent VB.NET course " & _
            "at IACT, we are delighted to inform you that you have " & _
            "passed with flying colours. Thank you for attending our " & _
            "and we wish you all the best for the future."
        wrdSelection.TypeText(StrToAdd)

        InsertLines(2)

        ' Create a string and insert it into the document.
        StrToAdd = "For information on additional courses, please visit " & _
                   "our website at "
        wrdSelection.TypeText(StrToAdd)
        ' Insert a hyperlink to the Web page.
        wrdSelection.Hyperlinks.Add(Anchor:=wrdSelection.Range, _
           Address:="http://www.iact.ie")
        ' Create a string and insert it in the document.
        StrToAdd = ". Thank you for your interest in the classes " & _
                   "offered, we look forward to hearing from you in the " & _
                   "again. " & vbCr & vbCr & _
                   "Sincerely," & vbCr & vbCr & vbCr & _
                   "Joe Bloggs" & vbCr & _
                   "Director IACT" & vbCr
        wrdSelection.TypeText(StrToAdd)

        ' Perform mail merge.
        wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument
        wrdMailMerge.Execute(False)


        ' Close the original form document.
        wrdDoc.Saved = True
        wrdDoc.Close(False)

        ' Release References.
        wrdSelection = Nothing
        wrdMailMerge = Nothing
        wrdMergeFields = Nothing
        wrdDoc = Nothing
        wrdApp = Nothing

        ' Clean up temp file.
        'System.IO.File.Delete("C:\DataDoc.doc")
    End Sub		

but I get the error 'Word was unable to open the data source' when I run the application.

Any ideas ????

Regards....
6foot7  19 hours 21 minutes ago
Just for information, I tried doing the mail merge process by opening up MS Word and selecting it from the menus, but when it came to choosing my Data Source, I was unable to choose the ContactsCB.mdf file. Not sure what this means, if anything !
6foot7  15 hours 51 minutes ago

You can use google to search for other answers

Custom Search

More Threads

• [02/03] Date Conversion Problem
• DataGridView questions
• How to insert a property in a user control?
• How to create a message pump in Console apps?
• How do I call a Public Sub on one form from a second form and get it to run?
• How to use System.Net.Mail.SmtpClient via SSL and Authentication?
• Check for existing records based on contents of one column in each row.
• OpenFileDialog To String
• Binding Navigator Save Button
• Strange things with com and ActiveX