如何在 Visual Basic 中使 Microsoft Word 自动执行邮件合并

文章翻译 文章翻译
文章编号: 220607 - 查看本文应用于的产品
展开全部 | 关闭全部

本文内容

概要

本文阐述如何借助 Microsoft Visual Basic 中的自动化功能来使用 Microsoft Word 创建邮件合并文档。

更多信息

有两种方法可以控制自动化服务器:使用晚期绑定或早期绑定。若使用晚期绑定,则只有在运行时才会绑定方法并且自动化服务器会声明为对象。若使用早期绑定,则您的应用程序在设计时便知道未来通信对象的确切类型,从而可将其对象声明为某个特定的类型。本示例使用早期绑定。由于早期绑定可以提供更高的性能和更好的类型安全性,因而在多数情况下被认为优于晚期绑定。

要早期绑定到自动化服务器,必须设置对该服务器类型库的引用。在 Visual Basic 中,此操作是通过“引用”对话框完成的。要打开“引用”对话框,请单击“项目”菜单上的“引用”。在本示例中,您必须先添加对 Word 类型库的引用,然后才能运行代码。

生成自动化示例

  1. 启动 Visual Basic,创建一个新的标准 EXE 项目。默认情况下会创建 Form1。
  2. 向 Form1 中添加一个“CommandButton”控件。
  3. 在“项目”菜单上,单击“引用”打开“引用”对话框。
  4. 选择“Microsoft Word 11.0 对象库”以创建对 Microsoft Office Word 2003 类型库的引用。对于 Word 2002,请选择“Microsoft Word 10.0 对象库”。对于 Word 2000,请选择“Microsoft Word 9.0 对象库”。对于 Word 97,请选择“Microsoft Word 8.0 对象库”。
  5. 单击“确定”关闭“引用”对话框。
  6. 在 Form1 的代码窗口中,添加以下代码:
    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
      wrdDoc.Select
      
      Set wrdSelection = wrdApp.Selection
      Set wrdMailMerge = wrdDoc.MailMerge
      
    ' Create the MailMerge Data file.
      CreateMailMergeDataFile
      
    ' 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"
      wrdSelection.TypeParagraph
    
      wrdMergeFields.Add wrdSelection.Range, "Address"
      wrdSelection.TypeParagraph
      wrdMergeFields.Add wrdSelection.Range, "CityStateZip"
        
      InsertLines 2
      
    ' Right align the line, and insert a date field
    ' with the current date.
      wrdSelection.ParagraphFormat.Alignment = _
            wdAlignParagraphRight
      wrdSelection.InsertDateTime _
            DateTimeFormat:="dddd, MMMM dd, yyyy", _
            InsertAsField:=False
            
      InsertLines 2
      
    ' Align the rest of the document.
      wrdSelection.ParagraphFormat.Alignment = _
            wdAlignParagraphJustify
    
      
    
      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, _
           NumColumns:=4
      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 = _
           wdGray25
        ' Format the first row in bold.
        .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", _
           "Instructor"
        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, _
         Address:="http://www.ee.stateu.tld"
      ' 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
      
    ' Clean up the 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
        wrdApp.Selection.TypeParagraph
      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 that contains the field data.
      wrdDoc.MailMerge.CreateDataSource Name:="C:\DataDoc.doc", _
            HeaderRecord:="FirstName, LastName, Address, CityStateZip"
    ' Open the file to insert the data.
      Set wrdDataDoc = wrdApp.Documents.Open("C:\DataDoc.doc")
      For iCount = 1 To 2
        wrdDataDoc.Tables(1).Rows.Add
      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.Save
      wrdDataDoc.Close False
    End Sub
    					
  7. 按 F5 键并单击该按钮以运行示例。

参考

有关 Office 自动化的更多信息,请访问下面的 Microsoft Office Development 支持网站:
http://support.microsoft.com/ofd

属性

文章编号: 220607 - 最后修改: 2006年5月24日 - 修订: 6.2
这篇文章中的信息适用于:
  • Microsoft Visual Basic 6.0 学习版
  • Microsoft Visual Basic 5.0 学习版
  • Microsoft Visual Basic 6.0 专业版
  • Microsoft Visual Basic 5.0 专业版
  • Microsoft Visual Basic 6.0 企业版
  • Microsoft Visual Basic 5.0 企业版
  • Microsoft Office Standard Edition 2003
  • Microsoft Office XP Developer Edition
  • Microsoft Office 2000 Developer Edition
  • Microsoft Office Word 2003
  • Microsoft Word 2002 标准版
  • Microsoft Word 2000 标准版
  • Microsoft Word 97 标准版
关键字:?
kbhowto kbautomation KB220607
Microsoft和/或其各供应商对于为任何目的而在本服务器上发布的文件及有关图形所含信息的适用性,不作任何声明。 所有该等文件及有关图形均"依样"提供,而不带任何性质的保证。Microsoft和/或其各供应商特此声明,对所有与该等信息有关的保证和条件不负任何责任,该等保证和条件包括关于适销性、符合特定用途、所有权和非侵权的所有默示保证和条件。在任何情况下,在由于使用或运行本服务器上的信息所引起的或与该等使用或运行有关的诉讼中,Microsoft和/或其各供应商就因丧失使用、数据或利润所导致的任何特别的、间接的、衍生性的损害或任何因使用而丧失所导致的之损害、数据或利润不负任何责任。

提供反馈

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com