How to automate Word from Visual Basic .NET to create a new document

For a Microsoft Visual C# .NET version of this article, see 316384 .

For a Microsoft Visual Basic 6.0 version of this article, see 313193 .

Summary

This step-by-step article describes how to create a new document in Word by using Automation from Visual Basic .NET.

Sample code

The sample code in this article demonstrates how to do the following:
  • Insert paragraphs with text and formatting.
  • Browse and modify various ranges within a document.
  • Insert tables, format tables, and populate the tables with data.
  • Add a chart.
To create a new Word document by using Automation from Visual Basic .NET, follow these steps:
  1. Start Microsoft Visual Studio .NET. On the File menu, click New and then click Project. Under Project types click Visual Basic Projects, then click Windows Application under Templates. Form1 is created by default.
  2. Add a reference to the Microsoft Word Object Library. To do this, follow these steps:
    1. On the Project menu, click Add Reference.
    2. On the COM tab, locate the Microsoft Word Object Library and click Select.

      Note Microsoft Office 2003 and later versions of Office include Primary Interop Assemblies (PIAs). Microsoft Office XP does not include PIAs, but they may be downloaded.
      For more information about Office XP PIAs, click the following article number to view the article in the Microsoft Knowledge Base:

      328912 Microsoft Office XP primary interop assemblies (PIAs) are available for download

    3. Click OK in the Add References dialog box to accept your selections. If you receive a prompt to generate wrappers for the libraries that you selected, click Yes.
  3. On the View menu, select Toolbox to display the Toolbox, and then add a button to Form1.
  4. Double-click Button1. The code window for the form appears.
  5. In the code window, replace the following code
        Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click

    End Sub
    with:
        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. Add the following code to the top of Form1.vb:
    Imports Word = Microsoft.Office.Interop.Word
  7. Press F5 to build and run the program.
After the code completes, examine the document that is created for you. The document contains two pages of formatted paragraphs, tables, and a chart.

Use a template

If you are using Automation to build documents that are all in a common format, you can benefit from starting the process with a new document that is based on a preformatted template. Using a template with your Word Automation client has two significant advantages over building a document from nothing:
  • You can have greater control over the formatting and placement of objects throughout your documents.
  • You can build your documents with less code.
By using a template, you can fine-tune the placement of tables, paragraphs, and other objects within the document, as well as include formatting on those objects. By using Automation, you can create a new document based on your template with code such as the following:
oWord.Documents.Add "<Path to your template>\MyTemplate.dot"
In your template, you can define bookmarks so that your Automation client can fill in variable text at a specific location in the document, as follows:
oDoc.Bookmarks.Item("MyBookmark").Range.Text = "Some Text Here"
Another advantage to using a template is that you can create and store formatting styles that you wish to apply at run time, as follows:
oDoc.Bookmarks.Item("MyBookmark").Range.Style = "MyStyle"
-or-
oWord.Selection.Style = "MyStyle"

References

For more information about using Visual Basic .NET to automate Microsoft Word, click the following article number to view the article in the Microsoft Knowledge Base:

301656 How to automate Word to perform a mail merge from Visual Basic .NET

For more information, see the following Microsoft Developer Network (MSDN) Web sites:
Properties

Article ID: 316383 - Last Review: Sep 15, 2010 - Revision: 1

Feedback