Microsoft KB Archive/301656

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

Article ID: 301656

Article Last Modified on 5/11/2007

-

APPLIES TO


 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft Office Word 2007
 * Microsoft Office Word 2003
 * Microsoft Word 2002 Standard Edition

-



This article was previously published under Q301656



SUMMARY
This article demonstrates how to use Microsoft Office Word to create a mail-merged document by using Automation from Microsoft Visual Basic .NET.



MORE INFORMATION
Automation is a process that allows applications that are written in languages such as Visual Basic .NET to programmatically control other applications. Automation to Word allows you to perform actions such as creating new documents, adding text to documents, and formatting documents. With Word and other Microsoft Office applications, virtually all of the actions that you can perform manually through the user interface can also be performed programmatically by using Automation.

Word exposes this programmatic functionality through an object model. The object model is a collection of classes and methods that serve as counterparts to the logical components of Word. For example, there is an Application object, a Document object, and a Paragraph object, each of which contain the functionality of those components in Word. To access the object model from Visual Basic .NET, you can set a project reference to the type library.

This article demonstrates how to set the proper project reference to the Word type library for Visual Basic .NET and provides sample code to automate Word.

Create an Automation client for Word
 Start Microsoft Visual Studio .NET. On the File menu, click New, and then click Project. Select Windows Application from the Visual Basic Project types. Form1 is created by default. Add a reference to Microsoft Word Object Library. To do this, follow these steps:  On the Project menu, click Add Reference. 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 Microsoft Office XP primary interop assemblies (PIAs) are available for download

 Click OK in the Add References dialog box to accept your selections.</ol> </li> On the View menu, select Toolbox to display the toolbox, and then add a button to Form1.</li> Double-click Button1. The code window for the form appears.</li>  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 &quot;LineNum&quot; blank lines. For iCount = 1 To LineNum wrdApp.Selection.TypeParagraph 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:=&quot;C:\DataDoc.doc&quot;, _             HeaderRecord:=&quot;FirstName, LastName, Address, CityStateZip&quot;) ' Open the file to insert data. wrdDataDoc = wrdApp.Documents.Open(&quot;C:\DataDoc.doc&quot;) For iCount = 1 To 2 wrdDataDoc.Tables.Item(1).Rows.Add Next iCount ' Fill in the data. FillRow(wrdDataDoc, 2, &quot;Steve&quot;, &quot;DeBroux&quot;, _             &quot;4567 Main Street&quot;, &quot;Buffalo, NY  98052&quot;) FillRow(wrdDataDoc, 3, &quot;Jan&quot;, &quot;Miksovsky&quot;, _             &quot;1234 5th Street&quot;, &quot;Charlotte, NC  98765&quot;) FillRow(wrdDataDoc, 4, &quot;Brian&quot;, &quot;Valentine&quot;, _             &quot;12348 78th Street  Apt. 214&quot;, &quot;Lubbock, TX  25874&quot;) ' Save and close the file. wrdDataDoc.Save wrdDataDoc.Close(False) 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(&quot;Word.Application&quot;) wrdApp.Visible = True

' Add a new document.

wrdDoc = wrdApp.Documents.Add wrdDoc.Select

wrdSelection = wrdApp.Selection wrdMailMerge = wrdDoc.MailMerge

' Create MailMerge Data file. CreateMailMergeDataFile

' Create a string and insert it in the document. StrToAdd = &quot;State University&quot; & vbCr & _ &quot;Electrical Engineering Department&quot; 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, &quot;FirstName&quot;) wrdSelection.TypeText(&quot; &quot;) wrdMergeFields.Add(wrdSelection.Range, &quot;LastName&quot;) wrdSelection.TypeParagraph

wrdMergeFields.Add(wrdSelection.Range, &quot;Address&quot;) wrdSelection.TypeParagraph wrdMergeFields.Add(wrdSelection.Range, &quot;CityStateZip&quot;)

InsertLines(2)

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

InsertLines(2)

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

wrdSelection.TypeText(&quot;Dear &quot;) wrdMergeFields.Add(wrdSelection.Range, &quot;FirstName&quot;) wrdSelection.TypeText(&quot;,&quot;) InsertLines(2)

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

InsertLines(2)

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

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 = _ Word.WdColorIndex.wdGray25 ' Bold the first row. .Rows.Item(1).Range.Bold = True ' Center the text in Cell (1,1). .Cell(1, 1).Range.Paragraphs.Alignment = _ Word.WdParagraphAlignment.wdAlignParagraphCenter

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

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

InsertLines(2)

' Create a string and insert it into the document. StrToAdd = &quot;For additional information regarding the &quot; & _ &quot;Department of Electrical Engineering, &quot; & _ &quot;you can visit our Web site at &quot; wrdSelection.TypeText(StrToAdd) ' Insert a hyperlink to the Web page. wrdSelection.Hyperlinks.Add(Anchor:=wrdSelection.Range, _          Address:=&quot;http://www.ee.stateu.tld&quot;) ' Create a string and insert it in the document. StrToAdd = &quot;. Thank you for your interest in the classes &quot; & _ &quot;offered in the Department of Electrical &quot; & _ &quot;Engineering. If you have any other questions, &quot; & _ &quot;please feel free to give us a call at &quot; & _ &quot;555-1212.&quot; & vbCr & vbCr & _ &quot;Sincerely,&quot; & vbCr & vbCr & _ &quot;Kathryn M. Hinsch&quot; & vbCr & _ &quot;Department of Electrical Engineering&quot; & 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(&quot;C:\DataDoc.doc&quot;) End Sub

</li>  Add the following to the top of Form1.vb. Imports Microsoft.Office.Interop </li> Press F5 to build and to run the program.</li> Click Button1 to start Word Automation and to perform the mail merge.</li></ol>

<div class="references_section">