HOWTO: Automate MailMerge in Word 2000 Using Visual J++ ( Java )

ID: Q244219


The information in this article applies to:
  • Microsoft Word 2000
  • Microsoft Visual J++, version 6.0


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 Solution Provider or the Microsoft fee-based consulting line at (800) 936-5200. For more information about Microsoft Certified Solution Providers, please see the following page on the World Wide Web:

http://www.microsoft.com/mcsp/
For more information about the support options available from Microsoft, please see the following page on the World Wide Web:

http://www.microsoft.com/support/supportnet/overview/overview.asp


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:"

  1. Start Visual J++. Specify a new Console application.


  2. Provide an appropriate name for the project. The sample code was developed in a project named "WordAuto."


  3. 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.


  4. 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:


  5. 
    /**
     * 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;
      }	 
    }			 
  6. In the code, change the line that says:


  7. 
    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.

  8. Press the F5 key to compile and run the sample


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


REFERENCES

For additional information about Automation of Office applications, please click the article numbers below to view the articles in the Microsoft Knowledge Base:

Q219430 HOWTO: Create/Format Excel Workbook Using Visual J++ Automation
Q220607 HOWTO: Automate Word 97/2000 to do Mail Merge from Visual Basic
Q220911 HOWTO: Automate Word 97 to Do Mail Merge with Visual C++ and MFC

Additional query words:

Keywords : kbAutomation kbVJ kbVJ600 kbWord kbGrpDSO kbDSupport kbword2000
Version : WINDOWS:2000,6.0
Platform : WINDOWS
Issue type : kbhowto


Last Reviewed: October 26, 1999
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.