如何從 Visual Basic 讓 Microsoft Word 自動執行合併列印

文章翻譯 文章翻譯
文章編號: 220607 - 檢視此文章適用的產品。
全部展開 | 全部摺疊

在此頁中

結論

本文將告訴您,如何使用 Microsoft Visual Basic 的「自動化」功能讓 Microsoft Word 建立合併列印文件。

其他相關資訊

控制「自動化」伺服器的方法有兩種:使用晚期繫結或早期繫結。使用晚期繫結時,方法要等到執行階段才會繫結,且「自動化」伺服器會宣告為「物件」。使用早期繫結時,應用程式會在設計階段就知道要溝通的確實物件型別,並且可以將其物件宣告為特定型別。本範例使用的是早期繫結,在大部分情況下早期繫結被認為是比較好的方法,因為它可以提供較佳的效能以及較好的型別安全。

如果要早期繫結至「自動化」伺服器,您必須設定該伺服器型別程式庫的參考。在 Visual Basic 中是透過 [參考] 對話方塊完成這項操作。如果要開啟 [參考] 對話方塊,請按一下 [專案] 功能表上的 [參考]。在本範例中,您必須新增 Word 的型別程式庫參考才能執行程式碼。

建置自動化範例

  1. 開啟 Visual Basic,並建立新的「標準 EXE」專案。根據預設會建立 Form1。
  2. 新增 [CommandButton] 控制項至 Form1。
  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月19日 - 版次: 6.2
這篇文章中的資訊適用於:
  • Microsoft Visual Basic 6.0 Learning Edition
  • Microsoft Visual Basic 5.0 Learning Edition
  • Microsoft Visual Basic 6.0 Professional Edition
  • Microsoft Visual Basic 5.0 Professional Edition
  • Microsoft Visual Basic 6.0 Enterprise Edition
  • Microsoft Visual Basic 5.0 Enterprise Edition
  • Microsoft Office Standard Edition 2003
  • Microsoft Office XP Developer Edition
  • Microsoft Office 2000 Developer Edition
  • Microsoft Office Word 2003
  • Microsoft Word 2002 Standard Edition
  • Microsoft Word 2000 Standard Edition
  • Microsoft Word 97 Standard Edition
關鍵字:?
kbautomation kbhowto 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