Visual Basic を使用して新しいドキュメントを作成して Microsoft Word を自動化する方法

概要

この記事では、Visual Basic の Automation を使用して Word で新しいドキュメントを作成する方法について説明します。

サンプル コード

この記事のサンプル コードでは、次の操作を行う方法を示します。

  • テキストと書式設定を含む段落を挿入します。
  • ドキュメント内のさまざまな範囲を参照および変更します。
  • テーブルを挿入し、テーブルを書式設定し、テーブルにデータを設定します。
  • グラフを追加します。

Visual Basic の Automation を使用して新しい Word 文書を作成するには、次の手順に従います。

  1. Visual Basic で、新しい Standard EXE プロジェクトを作成します。 Form1 は既定で作成されます。

  2. [ プロジェクト ] メニューの [参照] をクリックし、次のいずれかのオプションをクリックして、[OK] をクリック します

    • 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 をクリックします。

コードが完了したら、自動的に作成されたドキュメントを確認します。 ドキュメントには、書式設定された段落、テーブル、およびグラフの 2 つのページが含まれています。

テンプレートを使用する

Automation を使用して、すべて一般的な形式のドキュメントを作成する場合は、事前フォーマットされたテンプレートに基づく新しいドキュメントでプロセスを開始することでメリットを得ることができます。 Word Automation クライアントでテンプレートを使用すると、ドキュメントを何も作成しない場合と比べて、次の 2 つの大きな利点があります。

  • ドキュメント全体でオブジェクトの書式設定と配置をより細かく制御できます。
  • より少ないコードでドキュメントを作成できます。

テンプレートを使用すると、ドキュメント内のテーブル、段落、およびその他のオブジェクトの配置を微調整したり、それらのオブジェクトに書式設定を含めることができます。 Automation を使用すると、次のようなコードを使用して、テンプレートに基づいて新しいドキュメントを作成できます。

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

テンプレートでは、Automation クライアントがドキュメント内の特定の場所に次のように可変テキストを入力できるようにブックマークを定義できます。

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

テンプレートを使用するもう 1 つの利点は、実行時に適用する書式設定スタイルを作成して格納できることです。次のようにします。

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

or

oWord.Selection.Style = "MyStyle"

関連情報

詳細については、以下の記事番号をクリックして、Microsoft サポート技術情報の記事を表示してください。

285332 Visual Basic で Word 2002 を自動化して差し込み印刷を作成する方法

Visual Studio を使用した Microsoft Office Development

(c) Microsoft Corporation 2001、All Rights reserved。 Lori B. Turner(Microsoft Corporation) による寄稿。