Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


How to get mailmerge data from a word document using interop assemblies

Posted on 2008-11-06
Medium Priority
Last Modified: 2008-11-17
I have a word document (.doc), a merge file (.txt) and a header source file (.txt).
The word document is merged with the data from the merge file while the header source file tells about columns names.
Classic word mail merge.

I use word 2002 and the developed application is to be used where word 2002 is present. Furthermore I use Visual Studio, C# with
framework 2.0 and the Microsoft Interop Assemblies for Office XP.

The problem:
When I open the word file in microsoft word 2002, Word ask if I want to merge with the merge data file. If i rename the header source file
it tells me that it can't be found. So, this information must be included in the word document.

I'm trying to developing an application that finds the path of the mergefile and the header source file. But everytime I open
the word file and get the data from the mailmerge API both the connectionstring ned headersource fields are empty. Also word
doesn't ask me if I want to merge the data if i open the file from within my application.

Here's the simplicied code:

Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
app.Visible = true;

Document doc = null;

Object missing = Type.Missing;
Object trueValue = true;
Object falseValue = false;

Object path = "C:\\test\\test.doc";

doc = app.Documents.Open(ref path, ref missing, ref falseValue, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                    ref missing, ref missing, ref missing);

string s = doc.MailMerge.DataSource.ConnectString;

It seems like the information is somehow not loaded together with the word document. But I really can't figure out why.

Thanks in advance
Question by:Mortengr
  • 3
LVL 21

Expert Comment

ID: 22895762
this supplies step by step info:
Start Microsoft Visual Studio .NET.
2. On the File menu, click New, and then click Project. Select Windows Application from the Visual Basic Project types. Form1 is created by default.
3. Add a reference to Microsoft Word Object Library. To do this, follow these steps: a.  On the Project menu, click Add Reference.
b.  On the COM tab, locate Microsoft Word Object Library, and then click Select.

Note Microsoft Office 2003 includes Primary Interop Assemblies (PIAs). Microsoft Office XP does not include PIAs, but they can be downloaded. For more information about Office XP PIAs, click the following article number to view the article in the Microsoft Knowledge Base:
328912 (http://support.microsoft.com/kb/328912/) Microsoft Office XP primary interop assemblies (PIAs) are available for download  
c.  Click OK in the Add References dialog box to accept your selections.
4. On the View menu, select Toolbox to display the toolbox, and then add a button to Form1.
5. Double-click Button1. The code window for the form appears.
LVL 21

Expert Comment

ID: 22895769
In the code window, replace the following code.     Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
    End Sub
Use the following code.
 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


Accepted Solution

Mortengr earned 0 total points
ID: 22896182
Thanks for the answer. I know how to automatic merge the file using .net and the interop assemblies. I've also installed them on the same system running the application. More concrete the problem is:

IF I have a doc file which contains links to a mergefile and a header source, how do I extract these data paths from the document file without knowing the location of the mergefile and header source beforehand.

I need this functionality so users can select a doc file, and the application then moves the document together with linked files to another selected location.

Thanks in advance


Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

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

When you see single cell contains number and text, and you have to get any date out of it seems like cracking our heads.
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
Learn how to make your own table of contents in Microsoft Word using paragraph styles and the automatic table of contents tool. We'll be using the paragraph styles in Word’s Home toolbar to help you create a table of contents. Type out your initial …
The Relationships Diagram is a good way to get an overall view of what a database is keeping track of. It is also where relationships are defined. A relationship specifies how two tables connect to each other. As you build tables in Microsoft Ac…

564 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