Microsoft KB Archive/244219

= How To Automate MailMerge in Word 2000 Using Visual J++ ( Java ) =

Article ID: 244219

Article Last Modified on 11/23/2006

-

APPLIES TO


 * Microsoft Word 2000 Standard Edition
 * Microsoft Visual J++ 6.0 Standard Edition

-



This article was previously published under Q244219



SUMMARY
This article provides sample code that creates a mailmerge datasource, saves it as a text file, and then creates a mailmerge main document. The code then merges the address data of the datasource with the main document and sends the main document as an e-mail message.

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs. If you have limited programming experience, you may want to contact a Microsoft Certified Partner or the Microsoft fee-based consulting line at (800) 936-5200. For more information about Microsoft Certified Partners, please visit the following Microsoft Web site:

https://partner.microsoft.com/global/30000104

For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:

http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS



MORE INFORMATION
The Visual J++ project that includes the code sample below is a Console application. It requires that you have both of the products shown on the section of this article labeled "The information in this article applies to:"  Start Visual J++. Specify a new Console application. Provide an appropriate name for the project. The sample code was developed in a project named "WordAuto." When the project workspace opens, click Project on the menu bar, and click Add COM Wrapper. From the list box, check the box on the line for Microsoft Word 9.0 Object Library. Click OK and give the compiler time to generate the classes for the Word object model.  In the Project Explorer window, double-click the icon for Class 1.java to open the shell in the Code window. Then copy and paste the code below into that window, replacing the code and comments that are there: /** * This class can take a variable number of parameters on the command * line. Program execution begins with the main method. The class * constructor is not invoked unless an object of type 'Class1' * created in the main method. */ import msword9.*;      // Word object model support import com.ms.com.*;   // Variant & exception support

public class Class1 {     /**   * The main entry point for the application. *   * @param args Array of parameters passed to the application * via the command line. */  public static void main (String[] args) {   // Force COM objects to be created on the current thread // Otherwise, older VMs might not release all references // and Word might continue to run after you shut down. ComLib.declareMessagePumpThread; // Variable declarations msword9._Application appWord = null; msword9.Documents docs = null; msword9.Document adoc = null; msword9.Selection selection = null; msword9.Range range = null; msword9.Range range2 = null; msword9.Font font = null; msword9.Sections sections = null; msword9.Section section = null; msword9.MailMerge mailmerge = null; msword9.MailMergeFields mailmergefields = null; msword9.MailMergeField mailmergefield = null; msword9.MailMergeDataSource datasource = null; // Define the Word _Application object reference appWord = (_Application) new Application; // Bind it to WinWord.exe appWord = (_Application)appWord.getApplication; appWord.setVisible(true); docs = appWord.getDocuments; try { // This commented code will open an existing document /* adoc = docs.Open(variant("c:\\myTemp.doc" ),//FileName           variant( false ), //ConfirmConversions            variant( false ), //ReadOnly            variant( false ), //AddToRecentFiles            variant( "" ),    //passwordDocument            variant( "" ),    //password template            variant( false ), //revert            variant( "" ),    //write passworddocument            variant( "" ),    //write passwordtemplate            variant( 0),      //Format            variant( false ), // Encoding  - Word9 only            variant(true)     // Visible   - Word9 only            );*/

// Create the mailmerge datasource docs.Add(variant("Normal"), //template           variant(false),       //New template document?            variant(0),           //wdNewBlankDocument = 0            variant(true));       //visible

adoc = docs.Item(variant(1)); // Bind to the Document's object // reference selection = appWord.getSelection; // start at document's                                         // beginning range = selection.getRange; // First line is column headers, next lines are data range.setText("emailaddress,fullname\n"); range.Collapse(variant(1)); range.setText("someone@microsoft.com,Scott Cooper");

// Save as a CommaSeparatedValue (CSV) flat file adoc.SaveAs(variant("C:\\MrgSrc.txt"), //Filename           variant(4),       //wdFormatDOSText = 4            variant(false),   //LockComments            variant(""),      //Password            variant(false),   //Add to recent files            variant(""),      //Write password            variant(false),   //ReadOnlyRecommended            variant(false),   //Embed TrueType fonts            variant(false),   //SaveNativePictureFormat            variant(false),   //SaveForms data            variant(false));  //SaveAsAOCELetter

adoc.Close(variant(false),variant(false),variant(false)); // Create a new mailmerge target document docs.Add(variant("Normal"), //template           variant(false),       //New template document?            variant(0),           //wdNewBlankDocument = 0 //Wd 9            variant(true));       //visible                //Wd 9 //docs.AddOld(variant("Normal"), //AddOld = Word 97's Add      //    variant( false )); adoc = docs.Item(variant(1)); selection = appWord.getSelection; range = selection.getRange; // Only one Selection point in _app range = adoc.getContent;    // Create a Range object. // (Content is entire document.) range.setText("This is line 1, paragraph 1 of the new document"); range.Collapse(variant(0));   // 0=wdCollapseEnd, // 1=wdCollapseStart range.InsertParagraph;      // Move to a new paragraph range.InsertParagraph;      // Give it a double space font = range.getFont;       // define a font object reference float fsize = font.getSize; // Save initial state int ibold = font.getBold;   // ditto range.Collapse(variant(0));   // 0=wdCollapseEnd, // 1=wdCollapseStart range.InsertParagraph; range.InsertParagraph; range.Collapse(variant(0));   // collapse range to                                     // insertionpoint at end range.setText("Sample text string you added");

font.setName("Tahoma"); // range includes the entire last string font.setSize(24);      // so font changes affect the entire range font.setBold(-1);      // True range.Collapse(variant(0)); range.InsertParagraph; range.InsertParagraph; range.Collapse(variant(0)); range.setText("Back to the original font"); font.setSize(fsize);   // Restore original state font.setBold(ibold);   // ditto range = adoc.getContent;  // redefine the range object. range.Collapse(variant(1)); // move insertion point to                                   // doc's beginning range.InsertParagraph;    // add a new line at the beginning range = adoc.getContent;  // redefine the range object again range.Collapse(variant(1)); // move insertion point to                                   // doc's beginning adoc.SaveAs(variant("C:\\MyMailmergeMessage.doc"),                              variant(0),       //wdFormatDocument                               variant(false),   //LockComments                               variant(""),      // Password                               variant(true),    //AddToRecentFiles                               variant(""),      //WritePassword                               variant(false),   //ReadOnlyRecommended                               variant(true),    //EmbedTrueTypeFontsv                               variant(true),                                                  //SaveNativePictureFormat                               variant(true),    //SaveFormsData                               variant(true)     //SaveAsAOCELetter                                ); mailmerge = adoc.getMailMerge; // define mailmerge object //If necessary, specify the target document's type //mailmerge.setMainDocumentType(0); // wdFormLetters=0, wdNotAMergeDocument = -1, // wdMailingLabels = 1, wdEnvelopes = 2, wdCatalog = 3 try {       mailmerge.OpenDataSource("C:\\MrgSrc.txt", //string, not variant            variant(4),     //wdOpenFormatText            variant(false), //ConfirmConversions            variant(false), //ReadOnly            variant(false), //LinkToSource            variant(false), //AddToRecentFiles            variant(""),    //PasswordDocument            variant(""),    //PasswordTemplate            variant(false), //Revert            variant(""),    //WritePasswordDocument            variant(""),    //WritePasswordTemplate            variant(""),    //Connection            variant(""),    //SQLStatement            variant("")     //SQLStatement1            ); }     catch(Exception e)      { java.lang.System.out.println ("OpenDataSource failed with error" +e); }     mailmerge.EditMainDocument; mailmergefields = mailmerge.getFields; //MailMergeFields mailmergefield = mailmergefields.Add(range, "emailaddress"); mailmerge.setMailAddressFieldName("emailaddress"); mailmerge.setMailAsAttachment(false); mailmerge.setMailSubject("Subject line for email merge test 3"); mailmerge.setSuppressBlankLines(true); mailmerge.setDestination(2); // // wdMailMergeDestination(sendtoemail) datasource = mailmerge.getDataSource ; // // Returns MailMergeDataSource datasource.setFirstRecord(1); datasource.setLastRecord(2); try {       mailmerge.Execute(variant(true)); // Merge errors show in dialog }     catch(Exception e)      { java.lang.System.out.println ("Mailmerge Execute failed with error" +e); }     appWord.Quit(variant(false),variant(false),variant(false)); }   catch(Exception e)    { java.lang.System.out.println ("Doc startup failed with error" + e); }

} // Variant usages private static Variant variant( boolean b ) {   Variant v = new Variant; v.putBoolean( b ); return v; }

private static Variant variant( int i ) {   Variant v = new Variant; v.putInt(i); return v; }

private static Variant variant( String s ) {   Variant v = new Variant; v.putString (s); return v; } // Variant usage for optional parms private static Variant variant {   Variant v = new Variant; v.noParam; return v; } }                                In the code, change the line that says: range.setText("emailaddress,fullname\nsomeone@microsoft.com,Scott Cooper"); to replace the string someone@microsoft.com,Scott Cooper with your own e-mail address, a comma, and your own name.

 Press the F5 key to compile and run the sample</ol>

(c) Microsoft Corporation 1999, All Rights Reserved. Contributions by Chris Jensen, Microsoft Corporation.

<div class="references_section">