Microsoft KB Archive/316383

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

Article ID: 316383

Article Last Modified on 5/24/2007

-

APPLIES TO


 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition
 * Microsoft Office Word 2007
 * Microsoft Office Word 2003
 * Microsoft Word 2002 Standard Edition

-



This article was previously published under Q316383





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:  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. Add a reference to the Microsoft Word Object Library. To do this, follow these steps:  On the Project menu, click Add Reference. 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

 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.</ol> </li> On the View menu, select Toolbox to display the Toolbox, and then add a button to Form1.</li> Double-click Button1. The code window for the form appears.</li>  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(&quot;Word.Application&quot;) oWord.Visible = True oDoc = oWord.Documents.Add

'Insert a paragraph at the beginning of the document. oPara1 = oDoc.Content.Paragraphs.Add oPara1.Range.Text = &quot;Heading 1&quot; 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(&quot;\endofdoc&quot;).Range) oPara2.Range.Text = &quot;Heading 2&quot; oPara2.Format.SpaceAfter = 6 oPara2.Range.InsertParagraphAfter

'Insert another paragraph. oPara3 = oDoc.Content.Paragraphs.Add(oDoc.Bookmarks.Item(&quot;\endofdoc&quot;).Range) oPara3.Range.Text = &quot;This is a sentence of normal text. Now here is a table:&quot; 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(&quot;\endofdoc&quot;).Range, 3, 5) oTable.Range.ParagraphFormat.SpaceAfter = 6 For r = 1 To 3 For c = 1 To 5 oTable.Cell(r, c).Range.Text = &quot;r&quot; & r & &quot;c&quot; & 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(&quot;\endofdoc&quot;).Range) oPara4.Range.InsertParagraphBefore oPara4.Range.Text = &quot;And here's another table:&quot; 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(&quot;\endofdoc&quot;).Range, 5, 2) oTable.Range.ParagraphFormat.SpaceAfter = 6 For r = 1 To 5 For c = 1 To 2 oTable.Cell(r, c).Range.Text = &quot;r&quot; & r & &quot;c&quot; & 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(&quot;\endofdoc&quot;).Range.InsertParagraphAfter Do           oRng = oDoc.Bookmarks.Item(&quot;\endofdoc&quot;).Range oRng.ParagraphFormat.SpaceAfter = 6 oRng.InsertAfter(&quot;A line of text&quot;) 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(&quot;We're now on page 2. Here's my chart:&quot;) oRng.InsertParagraphAfter

'Insert a chart and change the chart. oShape = oDoc.Bookmarks.Item(&quot;\endofdoc&quot;).Range.InlineShapes.AddOLEObject( _           ClassType:=&quot;MSGraph.Chart.8&quot;, FileName _            :=&quot;&quot;, 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(&quot;\endofdoc&quot;).Range oRng.InsertParagraphAfter oRng.InsertAfter(&quot;THE END.&quot;)

'All done. Close this form. Me.Close

End Sub </li>  Add the following code to the top of Form1.vb: Imports Word = Microsoft.Office.Interop.Word </li> Press F5 to build and run the program.</li></ol>

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 &quot;<Path to your template>\MyTemplate.dot&quot; 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(&quot;MyBookmark&quot;).Range.Text = &quot;Some Text Here&quot; 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(&quot;MyBookmark&quot;).Range.Style = &quot;MyStyle&quot; -or- oWord.Selection.Style = &quot;MyStyle&quot;

<div class="references_section">