Microsoft KB Archive/301659

= How to automate Microsoft Word to perform Mail Merge from Visual C# =

Article ID: 301659

Article Last Modified on 1/31/2007

-

APPLIES TO


 * Microsoft Visual C# 2005 Express Edition
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Office Word 2003
 * Microsoft Word 2002 Standard Edition

-



This article was previously published under Q301659





For a Microsoft Visual Basic .NET version of this article, see 301656.



For a Microsoft Visual Basic 6.0 and Microsoft Visual Basic 5.0 version of this article, see 220607.



SUMMARY
This article demonstrates how to automate Microsoft Word to create a mail-merged document by using Microsoft Visual C# 2005 or Microsoft Visual C# .NET.



MORE INFORMATION
Automation is a process that allows applications that are written in languages such as Visual C# 2005 or Visual C# .NET to programmatically control other applications. Automation of 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 C# 2005 or Visual C# .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 C# .NET and provides sample code to automate Word.

Building the Automation Sample
 Start Microsoft Visual Studio 2005 or Microsoft Visual Studio .NET. On the File menu, click New, and then click Project. Select Windows Application from the Visual C# Project types. Form1 is created by default. Add a reference to Microsoft Word 11.0 Object Library in Visual Studio 2005 or to Microsoft Word Object Library in Visual Studio .NET. 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.

In Visual Studio 2005, locate Microsoft Word 11.0 Object Library on the COM tab.

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 INFO: Microsoft Office XP PIAs Are Available for Download

</li> Click OK in the Add References dialog box to accept your selections.</li></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 void button1_Click(object sender, System.EventArgs e) { } with: Word.Application wrdApp; Word._Document wrdDoc; Object oMissing = System.Reflection.Missing.Value; Object oFalse = false;

private void InsertLines(int LineNum) {   int iCount;

// Insert &quot;LineNum&quot; blank lines. for(iCount = 1; iCount<=LineNum; iCount++) {       wrdApp.Selection.TypeParagraph; } }

private void FillRow(Word._Document oDoc, int Row, string Text1,   string Text2, string Text3, string Text4) {   // Insert the data into the specific cell. oDoc.Tables[1].Cell(Row,1).Range.InsertAfter(Text1); oDoc.Tables[1].Cell(Row,2).Range.InsertAfter(Text2); oDoc.Tables[1].Cell(Row,3).Range.InsertAfter(Text3); oDoc.Tables[1].Cell(Row,4).Range.InsertAfter(Text4); }

private void CreateMailMergeDataFile {   Word._Document oDataDoc; int iCount;

Object oName = &quot;C:\\DataDoc.doc&quot;; Object oHeader = &quot;FirstName, LastName, Address, CityStateZip&quot;; wrdDoc.MailMerge.CreateDataSource(ref oName,ref oMissing,        ref oMissing,ref oHeader, ref oMissing, ref oMissing,         ref oMissing, ref oMissing, ref oMissing);

// Open the file to insert data. oDataDoc = wrdApp.Documents.Open(ref oName,ref oMissing,           ref oMissing, ref oMissing,ref oMissing,ref oMissing,            ref oMissing,ref oMissing,ref oMissing,ref oMissing,            ref oMissing,ref oMissing,ref oMissing,ref oMissing,            ref oMissing/*, ref oMissing */);

for (iCount=1; iCount<=2; iCount++) {       oDataDoc.Tables[1].Rows.Add(ref oMissing); }   // Fill in the data. FillRow(oDataDoc, 2, &quot;Steve&quot;, &quot;DeBroux&quot;,        &quot;4567 Main Street&quot;, &quot;Buffalo, NY  98052&quot;); FillRow(oDataDoc, 3, &quot;Jan&quot;, &quot;Miksovsky&quot;,        &quot;1234 5th Street&quot;, &quot;Charlotte, NC  98765&quot;); FillRow(oDataDoc, 4, &quot;Brian&quot;, &quot;Valentine&quot;,        &quot;12348 78th Street  Apt. 214&quot;,         &quot;Lubbock, TX  25874&quot;); // Save and close the file. oDataDoc.Save; oDataDoc.Close(ref oFalse, ref oMissing, ref oMissing); }

private void button1_Click(object sender, System.EventArgs e) { Word.Selection wrdSelection; Word.MailMerge wrdMailMerge; Word.MailMergeFields wrdMergeFields; Word.Table wrdTable; string StrToAdd;

// Create an instance of Word and make it visible. wrdApp = new Word.Application; wrdApp.Visible = true;

// Add a new document. wrdDoc = wrdApp.Documents.Add(ref oMissing,ref oMissing,       ref oMissing,ref oMissing); wrdDoc.Select;

wrdSelection = wrdApp.Selection; wrdMailMerge = wrdDoc.MailMerge;

// Create a MailMerge Data file. CreateMailMergeDataFile;

// Create a string and insert it into the document. StrToAdd = &quot;State University\r\nElectrical 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;

Object objDate = &quot;dddd, MMMM dd, yyyy&quot;; wrdSelection.InsertDateTime(ref objDate,ref oFalse,ref oMissing,        ref oMissing, ref oMissing); 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. wrdTable = wrdDoc.Tables.Add(wrdSelection.Range,9,4,        ref oMissing, ref oMissing); // Set the column widths. wrdTable.Columns[1].SetWidth(51, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[2].SetWidth(170, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[3].SetWidth(100, Word.WdRulerStyle.wdAdjustNone); wrdTable.Columns[4].SetWidth(111, Word.WdRulerStyle.wdAdjustNone); // Set the shading on the first row to light gray. wrdTable.Rows[1].Cells.Shading.BackgroundPatternColorIndex = Word.WdColorIndex.wdGray25; // Bold the first row. wrdTable.Rows[1].Range.Bold = 1; // Center the text in Cell (1,1). wrdTable.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;);

// Go to the end of the document. Object oConst1 = Word.WdGoToItem.wdGoToLine; Object oConst2 = Word.WdGoToDirection.wdGoToLast; wrdApp.Selection.GoTo(ref oConst1,ref oConst2,ref oMissing,ref oMissing); 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. Object oAddress = &quot;http://www.ee.stateu.tld&quot;; Object oRange = wrdSelection.Range; wrdSelection.Hyperlinks.Add(oRange, ref oAddress,ref oMissing,       ref oMissing, ref oMissing, ref oMissing); // Create a string and insert it into 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.\r\n\r\n&quot; + &quot;Sincerely,\r\n\r\n&quot; + &quot;Kathryn M. Hinsch\r\n&quot; + &quot;Department of Electrical Engineering \r\n&quot;; wrdSelection.TypeText(StrToAdd);

// Perform mail merge. wrdMailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument; wrdMailMerge.Execute(ref oFalse);

// Close the original form document. wrdDoc.Saved = true; wrdDoc.Close(ref oFalse,ref oMissing,ref oMissing);

// Release References. wrdSelection = null; wrdMailMerge = null; wrdMergeFields = null; wrdDoc = null; wrdApp = null;

// Clean up temp file. System.IO.File.Delete(&quot;C:\\DataDoc.doc&quot;); } Note You must change the code in Visual Studio 2005. By default, Visual C# adds one form to the project when you create a Windows Forms project. The form is named Form1. The two files that represent the form are named Form1.cs and Form1.designer.cs. You write the code in Form1.cs. The Form1.designer.cs file is where the Windows Forms Designer writes the code that implements all the actions that you performed by dragging and dropping controls from the Toolbox.

For more information about the Windows Forms Designer in Visual C# 2005, visit the following Microsoft Developer Network (MSDN) Web site:

http://msdn2.microsoft.com/en-us/library/ms173077.aspx

Note Microsoft Office Word 2003 has an additional argument for the Open method of the document. If you are using the Word 2003 PIA, remove the comment notation for the additional parameter for the Open method. </li>  Add the following to the top of Form1.cs: using Word = Microsoft.Office.Interop.Word; </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">