Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


Word merge from vb.net

Posted on 2016-07-18
Medium Priority
Last Modified: 2016-07-22
Need to merge the datatable values in  a word document with vb.net desktop application.
Have a format of letter.Need to insert fields from datatable into the word document fields.
Question by:RIAS
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
  • 2
LVL 13

Expert Comment

by:Dustin Saunders
ID: 41717677
To be clear, you are looking to do document generation off datatables created in VB?  Do you have an example Word Document template?  How are the variables listed in the document you want to replace?

Author Comment

ID: 41717684
I think it will be called mailmerge
LVL 13

Expert Comment

by:Dustin Saunders
ID: 41717691
I'm a bit confused now.  So the intent is to have a datatable that contains, for example:

name = John
last = Smith
city = Supertown

Open in new window

And your letter says:

Dear @name @last,

Thanks for living in @city.

-The Mayor

Open in new window

And it outputs for each datarow in datatable:

Dear John Smith,

Thanks for living in Supertown.

-The Mayor

Open in new window

Is that accurate?
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.


Author Comment

ID: 41717693
LVL 13

Accepted Solution

Dustin Saunders earned 1000 total points
ID: 41717723
Here is some sample code to get you going.

This will open your template file (oTemplate) and replace the variables with whatever you specify.  Just wrap this inside your "for each datarow in datatable" loop to set the variables you are replacing in the word document.  Then it saves to a variable file name (in the code here I manually made one) and closes/disposes of the word object.

        Dim oWord As Microsoft.Office.Interop.Word.Application
        Dim oDoc As Microsoft.Office.Interop.Word.Document
        Dim oTemplate As String = "C:\Users\DSaunders\Documents\_personal\EE\wordDocGeneration\letter.docx"

        oWord = CreateObject("Word.Application")
        oWord.Visible = True
        oDoc = oWord.Documents.Add

        oDoc = oWord.Documents.Open(oTemplate)

        oDoc.Content.Find.Execute(FindText:="[@name]", ReplaceWith:="John", Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
        oDoc.Content.Find.Execute(FindText:="[@last]", ReplaceWith:="Smith", Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)
        oDoc.Content.Find.Execute(FindText:="[@city]", ReplaceWith:="Supertown", Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)

        Dim outFile As String = "C:\Users\DSaunders\Documents\_personal\EE\wordDocGeneration\letter_" + "John" + "Smith" + ".docx"

        oDoc = Nothing
        oWord = Nothing

Open in new window

Sample word doc attached.

Author Comment

ID: 41717735
Cheers mate.. Will try and keep you posted
LVL 13

Expert Comment

by:Dustin Saunders
ID: 41717737
Don't forget to add a reference to the Microsoft Word Object Library! :)

Author Comment

ID: 41717740

Expert Comment

by:Valliappan AN
ID: 41719145
You could also perform the exact MailMerge functionality available in MS Word, from VB.Net as shown in this link:

(How to automate Word to perform a mail merge from Visual Basic .NET)

Extract from above link:

Imports Microsoft.Office.Interop

Dim wrdApp As Word.Application
    Dim wrdDoc As Word._Document

    Private Sub InsertLines(ByVal LineNum As Integer)
        Dim iCount As Integer

        ' Insert "LineNum" blank lines.
        For iCount = 1 To LineNum
        Next iCount
    End Sub

    Private Sub FillRow(ByVal Doc As Word.Document, ByVal Row As Integer, _
    ByVal Text1 As String, ByVal Text2 As String, _
    ByVal Text3 As String, ByVal Text4 As String)

        With Doc.Tables.Item(1)
            ' Insert the data in the specific cell.
            .Cell(Row, 1).Range.InsertAfter(Text1)
            .Cell(Row, 2).Range.InsertAfter(Text2)
            .Cell(Row, 3).Range.InsertAfter(Text3)
            .Cell(Row, 4).Range.InsertAfter(Text4)
        End With
    End Sub

    Private Sub CreateMailMergeDataFile()
        Dim wrdDataDoc As Word._Document
        Dim iCount As Integer

        ' Create a data source at C:\DataDoc.doc containing the field data.
        wrdDoc.MailMerge.CreateDataSource(Name:="C:\DataDoc.doc", _
              HeaderRecord:="FirstName, LastName, Address, CityStateZip")
        ' Open the file to insert data.
        wrdDataDoc = wrdApp.Documents.Open("C:\DataDoc.doc")
        For iCount = 1 To 2
        Next iCount
        ' Fill in the data.
        FillRow(wrdDataDoc, 2, "Steve", "DeBroux", _
              "4567 Main Street", "Buffalo, NY  98052")
        FillRow(wrdDataDoc, 3, "Jan", "Miksovsky", _
              "1234 5th Street", "Charlotte, NC  98765")
        FillRow(wrdDataDoc, 4, "Brian", "Valentine", _
              "12348 78th Street  Apt. 214", "Lubbock, TX  25874")
        ' Save and close the file.
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.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.
        wrdApp = CreateObject("Word.Application")
        wrdApp.Visible = True

        ' Add a new document.

        wrdDoc = wrdApp.Documents.Add()

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

        ' Create MailMerge Data file.

        ' Create a string and insert it in the document.
        StrToAdd = "State University" & vbCr & _
                    "Electrical Engineering Department"
        wrdSelection.ParagraphFormat.Alignment = _


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

        wrdMergeFields.Add(wrdSelection.Range, "Address")
        wrdMergeFields.Add(wrdSelection.Range, "CityStateZip")


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


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

        wrdSelection.TypeText("Dear ")
        wrdMergeFields.Add(wrdSelection.Range, "FirstName")

        ' Create a string and insert it into the document.
        StrToAdd = "Thank you for your recent request for next " & _
            "semester's class schedule for the Electrical " & _
            "Engineering Department. Enclosed with this " & _
            "letter is a booklet containing all the classes " & _
            "offered next semester at State University.  " & _
            "Several new classes will be offered in the " & _
            "Electrical Engineering Department next semester.  " & _
            "These classes are listed below."


        ' Insert a new table with 9 rows and 4 columns.
        wrdDoc.Tables.Add(wrdSelection.Range, NumRows:=9, _

        With wrdDoc.Tables.Item(1)
            ' Set the column widths.
            .Columns.Item(1).SetWidth(51, Word.WdRulerStyle.wdAdjustNone)
            .Columns.Item(2).SetWidth(170, Word.WdRulerStyle.wdAdjustNone)
            .Columns.Item(3).SetWidth(100, Word.WdRulerStyle.wdAdjustNone)
            .Columns.Item(4).SetWidth(111, Word.WdRulerStyle.wdAdjustNone)
            ' Set the shading on the first row to light gray.
            .Rows.Item(1).Cells.Shading.BackgroundPatternColorIndex = _
            ' Bold the first row.
            .Rows.Item(1).Range.Bold = True
            ' Center the text in Cell (1,1).
            .Cell(1, 1).Range.Paragraphs.Alignment = _

            ' Fill each row of the table with data.
            FillRow(wrdDoc, 1, "Class Number", "Class Name", "Class Time", _
            FillRow(wrdDoc, 2, "EE220", "Introduction to Electronics II", _
                      "1:00-2:00 M,W,F", "Dr. Jensen")
            FillRow(wrdDoc, 3, "EE230", "Electromagnetic Field Theory I", _
                      "10:00-11:30 T,T", "Dr. Crump")
            FillRow(wrdDoc, 4, "EE300", "Feedback Control Systems", _
                      "9:00-10:00 M,W,F", "Dr. Murdy")
            FillRow(wrdDoc, 5, "EE325", "Advanced Digital Design", _
                      "9:00-10:30 T,T", "Dr. Alley")
            FillRow(wrdDoc, 6, "EE350", "Advanced Communication Systems", _
                      "9:00-10:30 T,T", "Dr. Taylor")
            FillRow(wrdDoc, 7, "EE400", "Advanced Microwave Theory", _
                      "1:00-2:30 T,T", "Dr. Lee")
            FillRow(wrdDoc, 8, "EE450", "Plasma Theory", _
                      "1:00-2:00 M,W,F", "Dr. Davis")
            FillRow(wrdDoc, 9, "EE500", "Principles of VLSI Design", _
                      "3:00-4:00 M,W,F", "Dr. Ellison")
        End With

        ' Go to the end of the document.
        wrdApp.Selection.GoTo(Word.WdGoToItem.wdGoToLine, _


        ' Create a string and insert it into the document.
        StrToAdd = "For additional information regarding the " & _
                   "Department of Electrical Engineering, " & _
                   "you can visit our Web site at "
        ' Insert a hyperlink to the Web page.
        wrdSelection.Hyperlinks.Add(Anchor:=wrdSelection.Range, _
        ' Create a string and insert it in the document.
        StrToAdd = ".  Thank you for your interest in the classes " & _
                   "offered in the Department of Electrical " & _
                   "Engineering.  If you have any other questions, " & _
                   "please feel free to give us a call at " & _
                   "555-1212." & vbCr & vbCr & _
                   "Sincerely," & vbCr & vbCr & _
                   "Kathryn M. Hinsch" & vbCr & _
                   "Department of Electrical Engineering" & vbCr

        ' Perform mail merge.
        wrdMailMerge.Destination = _

        ' Close the original form document.
        wrdDoc.Saved = True

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

        ' Clean up temp file.
    End Sub

Open in new window

Thats an example, as you already have the template, you could use that template and mail merge.  Please let know if any questions.  

LVL 13

Expert Comment

by:Dustin Saunders
ID: 41719371
The mailmerge code from MSDN above isn't super modular so I advise on writing your own code.  You open up a lot more business functionality with your own code, i.e.

Give users a data dictionary (or write a word addin that has the variables in it users can insert).  Then anyone can write their own templates using [@variable] names and have it become a generative document.

If you put your letter into the code, it also means any time someone wants to make a change, the programmer has to go in and do it (and you've got better things to do than edit and proof letters).

Author Comment

ID: 41721052
its not working mate for my example.
Please find the doc attached.

Author Comment

ID: 41721056
Also it is a .doc file

Author Comment

ID: 41721058
need to populate values from datatable

       oDoc.Content.Find.Execute(FindText:="[a]", ReplaceWith:="Tjij :" & dtSQL.Rows(1)(2).ToString, Replace:=Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll)

Assisted Solution

by:Valliappan AN
Valliappan AN earned 1000 total points
ID: 41721102
>> If you put your letter into the code, it also means any time someone wants to make a change, the programmer has to go in and do it (and you've got better things to do than edit and proof letters).

You don't need to put your letter into the code. You could easily use your existing template and just merge the fields. Why reinvent the wheel? The example already mentioned, was just to some pointer to mail merge.

To use existing template you may use as in here (http://burnignorance.com/vb-net-tricks/working-with-mail-merge-word-document-using-vb-net/):

Dim objWord As New Object
objWord = CreateObject("Word.Application") ' Creating a word application
Dim objDoc As New Object
objDoc = CreateObject("Word.Document") ' Creating a word document object
objWord.application.WindowState = 0 ' set the word window in normal state (Const wdWindowStateNormal = 0)
objDoc = objWord.Documents.Add(DocsFolder.FullName & "\YOUR WORD DOC NAME") ' Add the mail merged document file
Dim NameBeforeWordMerge As String = objWord.ActiveDocument.Name
objWord.ActiveDocument.MailMerge.OpenDataSource("YOUR DATABASE PATH", _
               Connection:="dsn=DSN NAME; dbq=" & YOUR DATABASE PATH & ";", _
               sqlstatement:="select * from `" & tableName & "`")
With objWord.ActiveDocument.MailMerge
         .MailAsAttachment = False
         .MailAddressFieldName = ""
         .MailSubject = ""
        .SuppressBlankLines = True
         With .DataSource
               .FirstRecord = 1  ' Const wdDefaultFirstRecord = 1
               .LastRecord = -16 ' Const wdDefaultLastRecord = -16 (&HFFFFFFF0)
         End With
End With
 Dim NameAfterWordMerge As String = objWord.ActiveDocument.Name
objWord.Documents(NameBeforeWordMerge ).Close(0) ' close the template doc
objWord.Documents(NameAfterWordMerge ).Activate() ' activate the mail merged doc after record population

Open in new window


Author Closing Comment

ID: 41724187

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question