如何使用 Visual Basic 將 Microsoft Word 自動化以建立新檔

摘要

此逐步文章說明如何使用 Visual Basic 的自動化,在 Word 中建立新檔。

範例程式碼

本文中的範例程式碼示範如何執行下列動作:

  • 插入具有文字和格式的段落。
  • 流覽和修改檔內的各種範圍。
  • 插入資料表、格式化資料表,並在資料表中填入資料。
  • 新增圖表。

若要使用 Visual Basic 的自動化來建立新的 Word 檔,請遵循下列步驟:

  1. 在 Visual Basic 中,建立新的標準 EXE 專案。 根據預設,會建立 Form1。

  2. 在 [ 專案] 功能表上,按一下 [參考],按一下下列其中一個選項,然後按一下 [ 確定]

    • 針對 Office Word 2007,按一下 [Microsoft Word 12.0 物件程式庫]
    • 針對 Word 2003,按一下 [Microsoft Word 11.0 物件程式庫]
    • 針對 Word 2002,按一下 [Microsoft Word 10.0 物件程式庫]
    • 針對 Word 2000,按一下 [Microsoft Word 9.0 物件程式庫]
  3. 將 CommandButton 控制項新增至 Form1。

  4. 將下列程式碼新增至 Command1 的 Click 事件:

     Dim oWord As Word.Application
     Dim oDoc As Word.Document
     Dim oTable As Word.Table
     Dim oPara1 As Word.Paragraph, oPara2 As Word.Paragraph
     Dim oPara3 As Word.Paragraph, oPara4 As Word.Paragraph
     Dim oRng As Word.Range
     Dim oShape As Word.InlineShape
     Dim oChart As Object
     Dim Pos as Double
    
     'Start Word and open the document template.
     Set oWord = CreateObject("Word.Application")
     oWord.Visible = True
     Set oDoc = oWord.Documents.Add
    
     'Insert a paragraph at the beginning of the document.
     Set oPara1 = oDoc.Content.Paragraphs.Add
     oPara1.Range.Text = "Heading 1"
     oPara1.Range.Font.Bold = True
     oPara1.Format.SpaceAfter = 24    '24 pt spacing after paragraph.
     oPara1.Range.InsertParagraphAfter
    
     'Insert a paragraph at the end of the document.
     '** \endofdoc is a predefined bookmark.
     Set oPara2 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks("\endofdoc").Range)
     oPara2.Range.Text = "Heading 2"
     oPara2.Format.SpaceAfter = 6
     oPara2.Range.InsertParagraphAfter
    
     'Insert another paragraph.
     Set oPara3 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks("\endofdoc").Range)
     oPara3.Range.Text = "This is a sentence of normal text. Now here is a table:"
     oPara3.Range.Font.Bold = False
     oPara3.Format.SpaceAfter = 24
     oPara3.Range.InsertParagraphAfter
    
     'Insert a 3 x 5 table, fill it with data and make the first row
     'bold,italic.
     Dim r As Integer, c As Integer
     Set oTable = oDoc.Tables.Add(oDoc.Bookmarks("\endofdoc").Range, 3, 5)
     oTable.Range.ParagraphFormat.SpaceAfter = 6
     For r = 1 To 3
         For c = 1 To 5
             oTable.Cell(r, c).Range.Text = "r" & r & "c" & c
         Next
     Next
     oTable.Rows(1).Range.Font.Bold = True
     oTable.Rows(1).Range.Font.Italic = True
    
     'Add some text after the table.
     'oTable.Range.InsertParagraphAfter
     Set oPara4 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks("\endofdoc").Range)
     oPara4.Range.InsertParagraphBefore
     oPara4.Range.Text = "And here's another table:"
     oPara4.Format.SpaceAfter = 24
     oPara4.Range.InsertParagraphAfter
    
     'Insert a 5 x 2 table, fill it with data and change the column widths.
     Set oTable = oDoc.Tables.Add(oDoc.Bookmarks("\endofdoc").Range, 5, 2)
     oTable.Range.ParagraphFormat.SpaceAfter = 6
     For r = 1 To 5
         For c = 1 To 2
             oTable.Cell(r, c).Range.Text = "r" & r & "c" & c
         Next
     Next
     oTable.Columns(1).Width = oWord.InchesToPoints(2)   'Change width of columns 1 & 2.
     oTable.Columns(2).Width = oWord.InchesToPoints(3)
    
     'Keep inserting text. When you get to 7 inches from top of the
     'document, insert a hard page break.
     Pos = oWord.InchesToPoints(7)
     oDoc.Bookmarks("\endofdoc").Range.InsertParagraphAfter
     Do
         Set oRng = oDoc.Bookmarks("\endofdoc").Range
         oRng.ParagraphFormat.SpaceAfter = 6
         oRng.InsertAfter "A line of text"
         oRng.InsertParagraphAfter
     Loop While Pos >= oRng.Information(wdVerticalPositionRelativeToPage)
     oRng.Collapse (wdCollapseEnd)
     oRng.InsertBreak wdPageBreak
     oRng.Collapse wdCollapseEnd
     oRng.InsertAfter "We're now on page 2. Here's my chart:"
     oRng.InsertParagraphAfter
    
     'Insert a chart and change the chart.
     Set oShape = oDoc.Bookmarks("\endofdoc").Range.InlineShapes.AddOLEObject( _
         ClassType:="MSGraph.Chart.8", FileName _
         :="", LinkToFile:=False, DisplayAsIcon:=False)
     Set oChart = oShape.OLEFormat.Object
     oChart.charttype = 4 'xlLine = 4
     oChart.Application.Update
     oChart.Application.Quit
     '... If desired, you can proceed from here using the Microsoft Graph 
     'Object model on the oChart object to make additional changes to the
     'chart.
     oShape.Width = oWord.InchesToPoints(6.25)
     oShape.Height = oWord.InchesToPoints(3.57)
    
     'Add text after the chart.
     Set oRng = oDoc.Bookmarks("\endofdoc").Range
     oRng.InsertParagraphAfter
     oRng.InsertAfter "THE END."
    
     'All done. Unload this form.
     Unload Me
    
    
  5. 按 F5 執行程式,然後按一下 Command1。

程式碼完成之後,請檢查為您建立的檔。 檔包含兩頁格式化段落、表格和圖表。

使用範本

如果您使用自動化來建置通用格式的檔,您可以從使用以預先格式化範本為基礎的新檔來啟動程式中獲益。 將範本與您的 Word Automation 用戶端搭配使用,相較于從任何專案建置檔,有兩個顯著的優點:

  • 您可以更充分掌控整個檔中物件的格式設定和放置。
  • 您可以使用較少的程式碼來建置檔。

藉由使用範本,您可以微調檔中資料表、段落和其他物件的位置,以及在這些物件上包含格式設定。 藉由使用自動化,您可以使用如下的程式碼,根據您的範本建立新檔:

oWord.Documents.Add "<Path to your template>\MyTemplate.dot"

在範本中,您可以定義書簽,讓自動化用戶端可以在檔的特定位置填入變數文字,如下所示:

oDoc.Bookmarks("MyBookmark").Range.Text = "Some Text Here"

使用範本的另一個優點是您可以建立及儲存您想要在執行時間套用的格式化樣式,如下所示:

oDoc.Bookmarks("MyBookmark").Range.Style = "MyStyle"

oWord.Selection.Style = "MyStyle"

參考

如需其他資訊,請按一下下列文章編號,以檢視 Microsoft 知識庫中的文章:

285332 如何使用 Visual Basic 自動化 Word 2002 以建立合併列印

使用 Visual Studio 進行 Microsoft Office 開發

(c) Microsoft Corporation 2001, All Rights Reserved. 由 Lori B. 客戶、Microsoft Corporation 參與。