HOWTO: Automate Word 97/2000 to Perform Mail Merge from Visual Basic

ID: Q220607

The information in this article applies to:


This article demonstrates how to use Word 97 or Word 2000 to create a mail-merged document using Automation from Visual Basic.


There are two ways to control an Automation server: by using late binding or early binding. With late binding, methods are not bound until run-time and the Automation server is declared as Object. With early binding, your application knows at design-time the exact type of object it will be communicating with and can declare its objects as a specific type. This sample uses early binding, which is considered better in most cases because it affords greater performance and better type safety.

To early bind to an Automation server, you need to set a reference to that server's type library. In Visual Basic, this is done through the References dialog box found under the Project|References menu. For this sample, you will need to add a reference to the type library for Word 97 or Word 2000 before you can run the code. See the steps below on how to add the reference.

Building the Automation Sample

  1. Start Visual Basic and create a new Standard EXE project. Form1 will be created by default.

  2. Add a CommandButton to Form1.

  3. Select Project|References to bring up the References dialog. Select Microsoft Word 8.0 Object Library from the list to add a reference to Word 97. For Word 2000, select Microsoft Word 9.0 Object Library.

  4. Click OK to close the References dialog box.

  5. In the code window for Form1, insert the following code:

    Option Explicit
    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document
    Private Sub Command1_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
      Set wrdApp = CreateObject("Word.Application")
      wrdApp.Visible = True
    ' Add a new document
      Set wrdDoc = wrdApp.Documents.Add
      Set wrdSelection = wrdApp.Selection
      Set wrdMailMerge = wrdDoc.MailMerge
    ' Create MailMerge Data file
    ' Create a string and insert it into the document
      StrToAdd = "State University" & vbCr & _
               "Electrical Engineering Department"
      wrdSelection.ParagraphFormat.Alignment = wdAlignParagraphCenter
      wrdSelection.TypeText StrToAdd
      InsertLines 4
    ' Insert merge data
      wrdSelection.ParagraphFormat.Alignment = wdAlignParagraphLeft
      Set wrdMergeFields = wrdMailMerge.Fields
      wrdMergeFields.Add wrdSelection.Range, "FirstName"
      wrdSelection.TypeText " "
      wrdMergeFields.Add wrdSelection.Range, "LastName"
      wrdMergeFields.Add wrdSelection.Range, "Address"
      wrdMergeFields.Add wrdSelection.Range, "CityStateZip"
      InsertLines 2
    ' Right justify the line and insert a date field
    ' with the current date
      wrdSelection.ParagraphFormat.Alignment = _
      wrdSelection.InsertDateTime _
            DateTimeFormat:="dddd, MMMM dd, yyyy", _
      InsertLines 2
    ' Justify the rest of the document
      wrdSelection.ParagraphFormat.Alignment = _
      wrdSelection.TypeText "Dear "
      wrdMergeFields.Add wrdSelection.Range, "FirstName"
      wrdSelection.TypeText ","
      InsertLines 2
      ' Create a string and insert it into the document
      StrToAdd = "Thank you for your recent request for next " & _
          "semester's class schedule for the Electrical " & _
          "Engineering Department. Enclosed with this " & _
          "letter is a booklet containing all the classes " & _
          "offered next semester at State University.  " & _
          "Several new classes will be offered in the " & _
          "Electrical Engineering Department next semester.  " & _
          "These classes are listed below."
      wrdSelection.TypeText StrToAdd
      InsertLines 2
      ' Insert a new table with 9 rows and 4 columns
      wrdDoc.Tables.Add wrdSelection.Range, NumRows:=9, _
      With wrdDoc.Tables(1)
        ' Set the column widths
        .Columns(1).SetWidth 51, wdAdjustNone
        .Columns(2).SetWidth 170, wdAdjustNone
        .Columns(3).SetWidth 100, wdAdjustNone
        .Columns(4).SetWidth 111, wdAdjustNone
        ' Set the shading on the first row to light gray
        .Rows(1).Cells.Shading.BackgroundPatternColorIndex = _
        ' Bold the first row
        .Rows(1).Range.Bold = True
        ' Center the text in Cell (1,1)
        .Cell(1, 1).Range.Paragraphs.Alignment = wdAlignParagraphCenter
        ' Fill each row of the table with data
        FillRow wrdDoc, 1, "Class Number", "Class Name", "Class Time", _
        FillRow wrdDoc, 2, "EE220", "Introduction to Electronics II", _
           "1:00-2:00 M,W,F", "Dr. Jensen"
        FillRow wrdDoc, 3, "EE230", "Electromagnetic Field Theory I", _
           "10:00-11:30 T,T", "Dr. Crump"
        FillRow wrdDoc, 4, "EE300", "Feedback Control Systems", _
           "9:00-10:00 M,W,F", "Dr. Murdy"
        FillRow wrdDoc, 5, "EE325", "Advanced Digital Design", _
           "9:00-10:30 T,T", "Dr. Alley"
        FillRow wrdDoc, 6, "EE350", "Advanced Communication Systems", _
           "9:00-10:30 T,T", "Dr. Taylor"
        FillRow wrdDoc, 7, "EE400", "Advanced Microwave Theory", _
           "1:00-2:30 T,T", "Dr. Lee"
        FillRow wrdDoc, 8, "EE450", "Plasma Theory", _
           "1:00-2:00 M,W,F", "Dr. Davis"
        FillRow wrdDoc, 9, "EE500", "Principles of VLSI Design", _
           "3:00-4:00 M,W,F", "Dr. Ellison"
      End With
      ' Go to the end of the document
      wrdApp.Selection.GoTo wdGoToLine, wdGoToLast
      InsertLines 2
      ' Create a string and insert it into the document
      StrToAdd = "For additional information regarding the " & _
                 "Department of Electrical Engineering, " & _
                 "you can visit our Web site at "
      wrdSelection.TypeText StrToAdd
      ' Insert a hyperlink to the Web page
      wrdSelection.Hyperlinks.Add Anchor:=wrdSelection.Range, _
      ' Create a string and insert it into the document
      StrToAdd = ".  Thank you for your interest in the classes " & _
                 "offered in the Department of Electrical " & _
                 "Engineering.  If you have any other questions, " & _
                 "please feel free to give us a call at " & _
                 "555-1212." & vbCr & vbCr & _
                 "Sincerely," & vbCr & vbCr & _
                 "Kathryn M. Hinsch" & vbCr & _
                 "Department of Electrical Engineering" & vbCr
      wrdSelection.TypeText StrToAdd
    ' Perform mail merge
      wrdMailMerge.Destination = wdSendToNewDocument
      wrdMailMerge.Execute False
    ' Close the original form document
      wrdDoc.Saved = True
      wrdDoc.Close False
    ' Notify user we are done.
      MsgBox "Mail Merge Complete.", vbMsgBoxSetForeground
    ' Release References
      Set wrdSelection = Nothing
      Set wrdMailMerge = Nothing
      Set wrdMergeFields = Nothing
      Set wrdDoc = Nothing
      Set wrdApp = Nothing
    ' Cleanup temp file
      Kill "C:\DataDoc.doc"
    End Sub
    Public Sub InsertLines(LineNum As Integer)
      Dim iCount As Integer
    ' Insert "LineNum" blank lines
      For iCount = 1 To LineNum
      Next iCount
    End Sub
    Public Sub FillRow(Doc As Word.Document, Row As Integer, _
                       Text1 As String, Text2 As String, _
                       Text3 As String, Text4 As String)
      With Doc.Tables(1)
        ' Insert the data into 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
    Public 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:="C:\DataDoc.doc", _
            HeaderRecord:="FirstName, LastName, Address, CityStateZip"
    ' Open the file to insert data
      Set wrdDataDoc = wrdApp.Documents.Open("C:\DataDoc.doc")
      For iCount = 1 To 2
      Next iCount
    ' Fill in the data
      FillRow wrdDataDoc, 2, "Steve", "DeBroux", _
            "4567 Main Street", "Buffalo, NY  98052"
      FillRow wrdDataDoc, 3, "Jan", "Miksovsky", _
            "1234 5th Street", "Charlotte, NC  98765"
      FillRow wrdDataDoc, 4, "Brian", "Valentine", _
            "12348 78th Street  Apt. 214", "Lubbock, TX  25874"
    ' Save and close the file
      wrdDataDoc.Close False
    End Sub 
  7. Press the F5 key and click on the CommandButton to run the sample.


For more information on Office Automation, please visit the Microsoft Office Development support site at:

© Microsoft Corporation 1999, All Rights Reserved.
Contributions by Mark Durrett, Microsoft Corporation

Keywords          : kbAutomation kbVBp500 kbVBp600 kbWord kbGrpDSO kbOffice2000 kbword2000 
Version           : WINDOWS:2000,5.0,6.0,97; :
Platform          : WINDOWS 
Issue type        : kbhowto 

Last Reviewed: June 30, 1999