Microsoft KB Archive/308338

= Automate Microsoft Word to Perform a Mail Merge from Visual C++ .NET =

Article ID: 308338

Article Last Modified on 6/29/2007

-

APPLIES TO


 * Microsoft Visual C++ .NET 2002 Standard Edition
 * Microsoft Foundation Class Library 4.2
 * Microsoft Word 2000 Standard Edition
 * Microsoft Word 2002 Standard Edition
 * Microsoft Visual C++ .NET 2003 Standard Edition
 * Microsoft Visual Studio .NET 2003 Professional Edition
 * Microsoft Office Word 2003

-



This article was previously published under Q308338



For a Microsoft C# .NET version of this article, see 301659.

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



Note Microsoft Visual C++ .NET (2002) supports both the managed code model that is provided by the Microsoft .NET Framework and the unmanaged native Microsoft Windows code model. The information in this article applies only to unmanaged Visual C++ code.



SUMMARY
This article demonstrates how to create and manipulate a Word document from Visual C++ .NET and Microsoft Foundation Classes (MFC) by using Automation.



MORE INFORMATION
Automation is a process that allows applications that are written in languages such as Visual C++ .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 C++ .NET, you can set a project reference to the type library.

Building the Automation Sample
  Follow the steps in the &quot;Create an Automation Client&quot; section of the following Microsoft Knowledge Base article to create a basic Automation client:

307473 HOWTO: Use a Type Library for Office Automation from Visual C++ .NET

In step 4 of the article, select the Microsoft Word type library. The default location for Word 2000 is C:\Program Files\Microsoft Office\Office\Msword9.olb, the default location for Word 2002 is C:\Program Files\Microsoft Office\Office10\Msword.olb, and the default location for Word 2003 is C:\Program Files\Microsoft Office\Office11\MSWord.olb. Select the following Word interfaces:  _Application _Document Cell Cells Column</li> Columns</li> Documents</li> Hyperlinks</li> MailMerge</li> MailMergeFields</li> Paragraphs</li> Range</li> Row</li> Rows</li> Selection</li> Shading</li> Table</li> Tables</li></ul>

In step 6, add the following #include statements at the beginning of Autoprojectdlg.cpp: </li> In the IDD_AUTOPROJECT_DIALOG dialog box, right-click Run and select Add event handler. In the Event Handler Wizard, select the BN_CLICKED message type, and then click Add and Edit.</li>  Replace the following code void CAutoProjectDlg::OnBnClickedRun ( With Visual Studio .NET 1.1 you may not be able to rename the button to anything other than &quot;IDC_Button1&quot;. In that case the method will be named CAutoProject::OnBnClickedButton1.) {   // TO DO: Add your control notification handler code here. } with: void InsertLines(CSelection *pSelection, int NumLines) {   int iCount;
 * 1) include &quot;CApplication.h&quot;
 * 2) include &quot;CDocument0.h&quot;
 * 3) include &quot;CDocuments.h&quot;
 * 4) include &quot;CSelection.h&quot;
 * 5) include &quot;CParagraphs.h&quot;
 * 6) include &quot;CTable0.h&quot;
 * 7) include &quot;CTables0.h&quot;
 * 8) include &quot;CRange.h&quot;
 * 9) include &quot;CColumns0.h&quot;
 * 10) include &quot;CColumn.h&quot;
 * 11) include &quot;CRow.h&quot;
 * 12) include &quot;CRows.h&quot;
 * 13) include &quot;CCells.h&quot;
 * 14) include &quot;CCell.h&quot;
 * 15) include &quot;CShading.h&quot;
 * 16) include &quot;CHyperlinks.h&quot;
 * 17) include &quot;CMailMerge.h&quot;
 * 18) include &quot;CMailMergeFields.h&quot;

// Insert NumLines blank lines. for (iCount = 1; iCount <= NumLines; iCount++) pSelection->TypeParagraph; }

void FillRow(CTable0 *pTable,int Row, CString Text1,             CString Text2, CString Text3, CString Text4) {   CCell oCell; CRange oRange;

// Insert data into the specific cell. oCell = pTable->Cell(Row,1); oRange = oCell.get_Range; oRange.InsertAfter(Text1); oCell = pTable->Cell(Row,2); oRange = oCell.get_Range; oRange.InsertAfter(Text2); oCell = pTable->Cell(Row,3); oRange = oCell.get_Range; oRange.InsertAfter(Text3); oCell = pTable->Cell(Row,4); oRange = oCell.get_Range; oRange.InsertAfter(Text4); }

void CreateMailMergeDataFile(CApplication *pApp,CDocument0 *pDoc) { CDocument0 oDataDoc; CMailMerge oMailMerge; CDocuments oDocs; CTables0 oTables; CTable0 oTable; CRows oRows; int iCount; COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR), vtFalse((short)FALSE); // Create a data source that contains the field data at C:\DataDoc.doc. oMailMerge = pDoc->get_MailMerge; oMailMerge.CreateDataSource(COleVariant(&quot;C:\\DataDoc.doc&quot;),        vtOptional,vtOptional,        COleVariant(&quot;FirstName, LastName, Address,CityStateZip&quot;),        vtOptional, vtOptional,vtOptional,vtOptional,vtOptional); // Open the file to insert data. oDocs = pApp->get_Documents;

//WORD9: oDataDoc = oDocs.Open(COleVariant(&quot;C:\\DataDoc.doc&quot;),       vtOptional,vtOptional,vtOptional,vtOptional,       vtOptional,vtOptional,vtOptional,vtOptional,       vtOptional,vtOptional);

//WORD10: //oDataDoc = oDocs.Open(COleVariant(&quot;C:\\DataDoc.doc&quot;),  //     vtOptional,vtOptional,vtOptional,vtOptional,  //     vtOptional,vtOptional,vtOptional,vtOptional,  //     vtOptional,vtOptional,vtOptional,vtOptional,  //       vtOptional,vtOptional);

//WORD11: //oDataDoc = oDocs.Open(COleVariant(&quot;C:\\DataDoc.doc&quot;),  //     vtOptional,vtOptional,vtOptional,vtOptional,  //     vtOptional,vtOptional,vtOptional,vtOptional,  //     vtOptional,vtOptional,vtOptional,vtOptional,  //       vtOptional,vtOptional, vtOptional);

oTables = oDataDoc.get_Tables; oTable = oTables.Item(1); oRows = oTable.get_Rows; for (iCount=1; iCount<=2; iCount++) oRows.Add(vtOptional);

// Fill in the data. FillRow(&oTable, 2, &quot;Steve&quot;, &quot;DeBroux&quot;,        &quot;4567 Main Street&quot;, &quot;Buffalo, NY  98052&quot;); FillRow(&oTable, 3, &quot;Jan&quot;, &quot;Miksovsky&quot;,        &quot;1234 5th Street&quot;, &quot;Charlotte, NC  98765&quot;); FillRow(&oTable, 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(vtFalse,vtOptional,vtOptional); }

void CAutoProjectDlg::OnBnClickedRun // It may be OnBnClickedButton1 {   CApplication oWord; CDocuments oDocs; CDocument0 oDoc; CSelection oSelection; CParagraphs oParagraphs; CTables0 oTables; CTable0 oTable; CRange oRange; CColumns0 oColumns; CColumn oColumn; CRows oRows; CRow oRow;

CCells oCells; CCell oCell; CShading oShading; CHyperlinks oHyperlinks; CMailMerge oMailMerge; CMailMergeFields oMailMergeFields;

COleVariant vtOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR), vtTrue((short)TRUE), vtFalse((short)FALSE); CString StrToAdd;

// Create an instance of Word. if (!oWord.CreateDispatch(&quot;Word.Application&quot;)) { AfxMessageBox(&quot;Word failed to start!&quot;); } else { // Set the visible property. oWord.put_Visible(VARIANT_TRUE); // Add a new document. oDocs = oWord.get_Documents;

//WORD9: oDoc = oDocs.Add(vtOptional,vtOptional,vtOptional);

//WORD10 & WORD11: //oDoc = oDocs.Add(vtOptional,vtOptional,vtOptional,vtOptional);

CreateMailMergeDataFile(&oWord,&oDoc);

// Add the address header. StrToAdd = &quot;State University\r\nElectrical Engineering &quot; &quot;Department&quot;; oSelection = oWord.get_Selection;

oParagraphs = oSelection.get_Paragraphs; oParagraphs.put_Alignment(1); // 1 = wdAlignParagraphCenter oSelection.TypeText(StrToAdd);

InsertLines(&oSelection,4);

oParagraphs.put_Alignment(0); // 0 = wdAlignParagraphLeft

oMailMerge = oDoc.get_MailMerge; oMailMergeFields = oMailMerge.get_Fields; oMailMergeFields.Add(oSelection.get_Range,&quot;FirstName&quot;); oSelection.TypeText(&quot; &quot;); oMailMergeFields.Add(oSelection.get_Range,&quot;LastName&quot;); oSelection.TypeParagraph; oMailMergeFields.Add(oSelection.get_Range,&quot;Address&quot;); oSelection.TypeParagraph; oMailMergeFields.Add(oSelection.get_Range,&quot;CityStateZip&quot;);

InsertLines(&oSelection,4); // Set the paragraph alignment to Right justified. oParagraphs = oSelection.get_Paragraphs;

oParagraphs.put_Alignment(2); // 2 = wdAlignParagraphRight // Insert the current date.

//WORD9: oSelection.InsertDateTime(COleVariant(&quot;dddd, MMMM dd, yyyy&quot;),         vtFalse,vtOptional);

//WORD10 & WORD11: //oSelection.InsertDateTime(COleVariant(&quot;dddd, MMMM dd, yyyy&quot;),    //   vtFalse,vtOptional,vtOptional,vtOptional);

InsertLines(&oSelection,2);

// Reset the justification to Justify.

oParagraphs = oSelection.get_Paragraphs; oParagraphs.put_Alignment(3); // 3 = wdAlignParagraphJustify

oSelection.TypeText(&quot;Dear &quot;); oMailMergeFields.Add(oSelection.get_Range,&quot;FirstName&quot;); oSelection.TypeText(&quot;,&quot;);

InsertLines(&oSelection,2);

// Add the body of the message. 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 letter &quot; &quot;is a booklet containing all the classes offered &quot; &quot;next semester at State University. Several new &quot; &quot;classes will be offered in the Electrical &quot; &quot;Engineering Department next semester. These &quot; &quot;classes are listed below.&quot;; oSelection.TypeText(StrToAdd);

InsertLines(&oSelection,2); // Add a new table with 9 rows and 4 columns. oRange = oSelection.get_Range; oTables = oDoc.get_Tables; //WORD9: oTable = oTables.Add(oRange,9,4,vtOptional);

//WORD10 & WORD11: //oTable = oTables.Add(oRange,9,4,vtOptional,vtOptional);

// Set the width of each column. oColumns = oTable.get_Columns;

//BEGIN WORD9: oColumn = oColumns.Item(1); oColumn.put_Width(60.0,0); // 0 = wdAdjustNone oColumn = oColumns.Item(2); oColumn.put_Width(182.0,0); // 0 = wdAdjustNone oColumn = oColumns.Item(3); oColumn.put_Width(100.0,0); // 0 = wdAdjustNone oColumn = oColumns.Item(4); oColumn.put_Width(111.0,0); // 0 = wdAdjustNone //END WORD9

/*   //BEGIN WORD10 & WORD11: oColumn = oColumns.Item(1); oColumn.put_Width(60.0); // 0 = wdAdjustNone oColumn = oColumns.Item(2); oColumn.put_Width(182.0); // 0 = wdAdjustNone oColumn = oColumns.Item(3); oColumn.put_Width(100.0); // 0 = wdAdjustNone oColumn = oColumns.Item(4); oColumn.put_Width(111.0); // 0 = wdAdjustNone //END WORD10 & WORD11 */

// Set the shading for row 1 to wdGray25. oRows = oTable.get_Rows; oRow = oRows.Item(1); oCells = oRow.get_Cells; oShading = oCells.get_Shading; oShading.put_BackgroundPatternColorIndex(16); // 16 = wdGray25

// Turn on bold formatting for the first row. oRange = oRow.get_Range; oRange.put_Bold(TRUE);

// Set the alignment for cell (1,1) to Center. oCell = oTable.Cell(1,1); oRange = oCell.get_Range; oParagraphs = oRange.get_Paragraphs; oParagraphs.put_Alignment(1); // 1 = wdAlignParagraphCenter

// Fill in the class schedule data. FillRow(&oTable,1,&quot;Class Number&quot;,&quot;Class Name&quot;,        &quot;Class Time&quot;,&quot;Instructor&quot;); FillRow(&oTable,2, &quot;EE220&quot;, &quot;Introduction to Electronics II&quot;,         &quot;1:00-2:00 M,W,F&quot;, &quot;Dr. Jensen&quot;); FillRow(&oTable,3, &quot;EE230&quot;, &quot;Electromagnetic Field Theory I&quot;,         &quot;10:00-11:30 T,T&quot;, &quot;Dr. Crump&quot;); FillRow(&oTable,4, &quot;EE300&quot;, &quot;Feedback Control Systems&quot;,         &quot;9:00-10:00 M,W,F&quot;, &quot;Dr. Murdy&quot;); FillRow(&oTable,5, &quot;EE325&quot;, &quot;Advanced Digital Design&quot;,         &quot;9:00-10:30 T,T&quot;, &quot;Dr. Alley&quot;); FillRow(&oTable,6, &quot;EE350&quot;, &quot;Advanced Communication Systems&quot;,         &quot;9:00-10:30 T,T&quot;, &quot;Dr. Taylor&quot;); FillRow(&oTable,7, &quot;EE400&quot;, &quot;Advanced Microwave Theory&quot;,         &quot;1:00-2:30 T,T&quot;, &quot;Dr. Lee&quot;); FillRow(&oTable,8, &quot;EE450&quot;, &quot;Plasma Theory&quot;,         &quot;1:00-2:00 M,W,F&quot;, &quot;Dr. Davis&quot;); FillRow(&oTable,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. oSelection.GoTo(COleVariant((short)3), // 3 = wdGoToLine   COleVariant((short)-1),vtOptional,vtOptional);  // -1 = wdGoToLast

InsertLines(&oSelection,2);

// Add closing text. StrToAdd = &quot;For additional information regarding the &quot; &quot;Department of Electrical Engineering, &quot; &quot;you can visit our website at &quot;; oSelection.TypeText(StrToAdd);

// Add a hyperlink to the home page. oHyperlinks = oSelection.get_Hyperlinks;

oHyperlinks.Add(oSelection.get_Range,           COleVariant(&quot;http://www.ee.stateu.tld&quot;),vtOptional,            vtOptional,vtOptional,vtOptional);

// Finish adding closing text. 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 (999) &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;; oSelection.TypeText(StrToAdd);

// Perform mail merge. oMailMerge.put_Destination(0); // 0 = wdSendToNewDocument oMailMerge.Execute(vtFalse);

// Close the original form document. oDoc.put_Saved(TRUE); oDoc.Close(vtFalse,vtOptional,vtOptional); } } NOTE: As written, this code uses the Word 9.0 object library. When you added references to your project, if you selected the Word 10.0 object library or Word 11 instead of the Word 9.0 object library, search the code for comments that contain &quot;//WORD10&quot; or &quot;//WORD11, or //WORD10 & WORD11and uncomment the line or lines of code to which the comment refers. Likewise, search the code for comments that contain &quot;//WORD9&quot; and comment the line or lines of code to which the comment refers.

</li> <li>Be sure to implement step 5. in the list under the heading &quot;Create Automation Client&quot; from the article mentioned above, i.e.

Article ID 307473 &quot;HOWTO: Use a Type Library for Office Automation from Visual C++ .NET.</li> <li>Press F5 to build and run the program.</li> <li>Click Run. The Automation client starts Word and creates a set of form letters from a mail merge.</li></ol>

<div class="references_section">