メイン コンテンツへスキップ
サポート
Microsoft アカウントでサインイン
サインインまたはアカウントを作成してください。
こんにちは、
別のアカウントを選択してください。
複数のアカウントがあります
サインインに使用するアカウントを選択してください。

この記事の Microsoft Visual C# .NET バージョンについては、「 316384」を参照してください。
 

この記事の Microsoft Visual Basic 6.0 バージョンについては、「 313193」を参照してください。
 

概要

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

サンプル コード

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

  • テキストと書式設定を含む段落を挿入します。

  • ドキュメント内のさまざまな範囲を参照および変更します。

  • テーブルを挿入し、テーブルの書式設定を行い、テーブルにデータを設定します。

  • グラフを追加します。

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

  1. Microsoft Visual Studio .NET を起動します。 [ファイル] メニューの [新規] をクリックし、[プロジェクト] をクリックします。 [プロジェクトの種類] で [Visual Basic プロジェクト] をクリックし、[テンプレート] の [Windows アプリケーション] をクリックします。 Form1 は既定で作成されます。

  2. Microsoft Word オブジェクト ライブラリへの参照を追加します。 この場合、次の手順を実行します。

    1. [プロジェクト] メニューの [参照の追加] をクリックします。

    2. [COM] タブで、Microsoft Word オブジェクト ライブラリを見つけて、[選択] をクリックします。

      注 Microsoft Office 2003 以降のバージョンの Office には、プライマリ相互運用機能アセンブリ (PIA) が含まれています。 Microsoft Office XP には PIA は含まれていませんが、ダウンロードされる場合があります。
       

    3. [参照の追加] ダイアログ ボックスで [OK] をクリックして、選択内容を受け入れます。 選択したライブラリのラッパーを生成するように求めるメッセージが表示されたら、[はい] をクリックします。

  3. [表示] メニューの [ツールボックス] を選択してツールボックスを表示し、Form1 にボタンを追加します。

  4. Button1 をダブルクリックします。 フォームのコード ウィンドウが表示されます。

  5. コード ウィンドウで、次のコードを置き換えます

        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
  6. Form1.vb の先頭に次のコードを追加します。

    Imports Word = Microsoft.Office.Interop.Word
  7. F5 キーを押してプログラムをビルドして実行します。

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

テンプレートを使用する

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

  • ドキュメント全体のオブジェクトの書式設定と配置をより詳しく制御できます。

  • コードを少なくしてドキュメントをビルドできます。

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

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

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

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

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

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

または

oWord.Selection.Style = "MyStyle"

関連情報

Visual Basic .NET を使用して Microsoft Word を自動化する方法の詳細については、次の記事番号をクリックして、Microsoft サポート技術情報の記事を表示してください。

301656 Visual Basic .NET から差し込み印刷を実行するように Word を自動化する方法

ヘルプを表示

その他のオプションが必要ですか?

サブスクリプションの特典の参照、トレーニング コースの閲覧、デバイスのセキュリティ保護方法などについて説明します。

コミュニティは、質問をしたり質問の答えを得たり、フィードバックを提供したり、豊富な知識を持つ専門家の意見を聞いたりするのに役立ちます。

この情報は役に立ちましたか?

言語の品質にどの程度満足していますか?
どのような要因がお客様の操作性に影響しましたか?
[送信] を押すと、Microsoft の製品とサービスの改善にフィードバックが使用されます。 IT 管理者はこのデータを収集できます。 プライバシーに関する声明。

フィードバックをいただき、ありがとうございます。

×