本文將逐步告訴您如何使用 Visual Basic .NET 中的「自動化」在 Word
中建立新文件。
範例程式碼
本文中的範例程式碼會示範如何執行下列操作:
- 以文字和格式插入段落。
- 瀏覽和修改文件中的各種範圍。
- 插入資料表、格式化資料表及將資料填入資料表。
- 新增圖表。
如果要使用 Visual Basic .NET 中的「自動化」建立新的 Word 文件,請依照下列步驟執行:
- 啟動 Microsoft Visual Studio .NET。在 [檔案] 功能表中,按一下 [新增],再按一下 [專案]。在 [專案類型] 下方,按一下 [Visual Basic 專案],再按一下 [範本] 下的 [Windows 應用程式]。根據預設,會建立 Form1。
- 在 [Microsoft Word Object Library] 中新增參考。如果要執行這項操作,請依照下列步驟執行:
- 按一下 [專案] 功能表上的 [加入參考]。
- 在 [COM] 索引標籤上找出 [Microsoft Word Object Library],然後按一下 [選取]。
注意 Microsoft Office 2003 包含「主要的 Interop 組件」(PIA)。Microsoft Office XP
不包含 PIA,不過這些組件可以由下載取得。
如需有關 Office XP PIA 的詳細資訊,請按一下下面的文件編號,檢視「Microsoft
知識庫」中的文件:328912?
(http://support.microsoft.com/kb/328912/
)
Microsoft Office XP primary interop assemblies (PIAs) are available for download
- 按一下 [加入參考] 對話方塊中的 [確定] 以接受您的選擇。如果您收到提示要求您為選取的程式庫產生包裝函式,請按一下 [是]。
- 在 [檢視] 功能表上,選擇 [工具箱] 以顯示 [工具箱],並在 Form1 新增一個按鈕。
- 按兩下 [Button1]。即顯示該表單的程式碼視窗。
- 在程式碼視窗中,將下列程式碼
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
End Sub 取代為:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.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.
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add
'Insert a paragraph at the beginning of the document.
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.
oPara2 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\endofdoc").Range)
oPara2.Range.Text = "Heading 2"
oPara2.Format.SpaceAfter = 6
oPara2.Range.InsertParagraphAfter()
'Insert another paragraph.
oPara3 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\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 and italic.
Dim r As Integer, c As Integer
oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\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.Item(1).Range.Font.Bold = True
oTable.Rows.Item(1).Range.Font.Italic = True
'Add some text after the table.
'oTable.Range.InsertParagraphAfter()
oPara4 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item("\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.
oTable = oDoc.Tables.Add(oDoc.Bookmarks.Item("\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.Item(1).Width = oWord.InchesToPoints(2) 'Change width of columns 1 & 2
oTable.Columns.Item(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.Item("\endofdoc").Range.InsertParagraphAfter()
Do
oRng = oDoc.Bookmarks.Item("\endofdoc").Range
oRng.ParagraphFormat.SpaceAfter = 6
oRng.InsertAfter("A line of text")
oRng.InsertParagraphAfter()
Loop While Pos >= oRng.Information(Word.WdInformation.wdVerticalPositionRelativeToPage)
oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
oRng.InsertBreak(Word.WdBreakType.wdPageBreak)
oRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
oRng.InsertAfter("We're now on page 2. Here's my chart:")
oRng.InsertParagraphAfter()
'Insert a chart and change the chart.
oShape = oDoc.Bookmarks.Item("\endofdoc").Range.InlineShapes.AddOLEObject( _
ClassType:="MSGraph.Chart.8", FileName _
:="", LinkToFile:=False, DisplayAsIcon:=False)
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.
oRng = oDoc.Bookmarks.Item("\endofdoc").Range
oRng.InsertParagraphAfter()
oRng.InsertAfter("THE END.")
'All done. Close this form.
Me.Close()
End Sub - 將下列程式碼新增至 Form1.vb 頂端:
Imports Word = Microsoft.Office.Interop.Word
- 按下 F5 以建立並執行程式。
在程式碼完成之後,檢查為您所建立的文件。文件包含兩頁格式化的段落、資料表和圖表。
使用範本
如果您正使用「自動化」建立一般格式的文件,只要使用以預先格式化的範本為基礎的新文件,您就能輕易地開始這個程序。使用您的「Word
自動化」用戶端的範本對於從無開始到建立新文件有兩個顯著的優點:
- 您可以擁有更多的控制權在格式化文件和於文件中放置物件。
- 您可以使用較少的程式碼建立文件。
經由使用範本,您可以微調文件中的表格、段落和其他物件的放置位置,以及在這些物件中加入格式。經由使用「自動化」,您可以使用類似下列的程式碼,根據您的範本建立新文件
oWord.Documents.Add "<Path to your template>\MyTemplate.dot"
在範本中,您可以定義書籤,讓「自動化」用戶端可以在文件中的特定位置填入變數文字,如下所示:
oDoc.Bookmarks.Item("MyBookmark").Range.Text = "Some Text Here" 另一個使用範本的優點,是您可以建立和儲存希望在執行階段套用的格式化樣式,如下所示:
oDoc.Bookmarks.Item("MyBookmark").Range.Style = "MyStyle" -或-
oWord.Selection.Style = "MyStyle"
如需有關如何使用 Visual Basic
.NET 自動化 Microsoft Word 的詳細資訊,請按一下下面的文件編號,檢視「Microsoft 知識庫」中的文件:
301656?
(http://support.microsoft.com/kb/301656/
)
How To Automate Microsoft Word to Perform a Mail Merge from Visual Basic .NET
如需更多資訊,請參閱下列 Microsoft Developer Network (MSDN) 網站: