Share via


VB.Net Using a Word Templte to Create a Document

Question

Saturday, September 8, 2012 5:08 AM

Hi Guys,

I'm trying to write a VB.Net app which will generate a Word Document using a set Word Template (e.g. ApprovalTemplate.dot) stored in a shared folder. The document get's created fine, the application runs without any errors. When I open the document the programme created it appears fine just as I want, However when I go to close the document I receive a prompt asking if I want to save the changes to my template file (ApprovalTemplate.dot)

I'd love some feedback, this is the first time I've tried to Create a Word file through VB.Net.

Code:

Dim objApp As Microsoft.Office.Interop.Word.Application = New Microsoft.Office.Interop.Word.Application
            Dim objDoc As Microsoft.Office.Interop.Word.Document = New Microsoft.Office.Interop.Word.Document

            Dim rName As String = My.Computer.Name
            Dim lSlash As Integer = rName.LastIndexOf("\")
            Dim fName As String = rName.Substring(lSlash + 1)

            Dim nl As Char = ControlChars.NewLine


            objDoc = objApp.Documents.Add(AData & "\UAT\ApprovalTemplate.dot")
            objDoc.Activate()
            
          
            objApp.Selection.TypeParagraph()
            objApp.Selection.TypeText("My test is in Here")
            objApp.Selection.TypeParagraph()
            objApp.Selection.TypeText(nl & nl & nl & nl & "Name: " & fName & "    Date: " & SignDate)
            objApp.Selection.TypeParagraph()
            Dim MyRange As Microsoft.Office.Interop.Word.Range = objDoc.Content
            MyRange.Words(2).Bold = True
            MyRange.Words(6).Bold = True
            
            
            objDoc.SaveAs(strSavePath)
            
            objDoc.Close()
            objApp.Quit()
            objDoc = Nothing
            objApp = Nothing

Thanks Guys

PLEASE MARK ANY ANSWERS TO HELP OTHERS Blog: rorymon.com Twitter: @Rorymon

All replies (12)

Saturday, September 8, 2012 2:47 PM

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.
    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.

On the COM%3


Saturday, September 8, 2012 4:51 PM

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.
    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 (http://support.microsoft.com/kb/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"

Saturday, September 8, 2012 7:05 PM

Looking at what I have could you tell me what I'm missing? Why does it keep the file hung up?

I have seen the attached code before

PLEASE MARK ANY ANSWERS TO HELP OTHERS Blog: rorymon.com Twitter: @Rorymon


Monday, September 10, 2012 6:17 AM

Hi Rorymon,

Welcome to the MSDN forum.

Microsoft provides a special forum to deal with Word issue. For better support, I will move this thread to Word for Developers forum. It will cost a little time to involve the members in this forum. I appreciate your patience.

Sorry for any inconvenience and have a nice day.

Mark Liu-lxf [MSFT]
MSDN Community Support | Feedback to us


Monday, September 10, 2012 6:54 AM

Hi Rorymon, 

I've tried your code however I could not reproduce your scenario. Have you tried objDoc.SaveAa2() method?

I'm looking forward to your reply.

Best regards,
Quist

Quist Zhang [MSFT]
MSDN Community Support | Feedback to us


Monday, September 10, 2012 7:45 AM | 1 vote

Hi Rorymon

<<However when I go to close the document I receive a prompt asking if I want to save the changes to my template file (ApprovalTemplate.dot)>>

Depending on what the template contains and what your code does, it can happen that something is written back to the template to "dirty" it - meaning Word thinks it needs to be saved. Usually, that is not the case, so it's enough to tell Word to ignore the "dirtiness". You can do that using the SAVED property. Something like this:
   objDoc.AttachedTemplate.Saved = True

Cindy Meister, VSTO/Word MVP, my blog


Monday, September 10, 2012 4:01 PM

I have tried this with the same reuslts I'm afraid. Thanks.

PLEASE MARK ANY ANSWERS TO HELP OTHERS Blog: rorymon.com Twitter: @Rorymon


Monday, September 10, 2012 4:02 PM

Hi Rorymon

<<However when I go to close the document I receive a prompt asking if I want to save the changes to my template file (ApprovalTemplate.dot)>>

Depending on what the template contains and what your code does, it can happen that something is written back to the template to "dirty" it - meaning Word thinks it needs to be saved. Usually, that is not the case, so it's enough to tell Word to ignore the "dirtiness". You can do that using the SAVED property. Something like this:
   objDoc.AttachedTemplate.Saved = True

Cindy Meister, VSTO/Word MVP, my blog

I think I tried that...actually I'm not sure I may have just had doc saved. I'll try the template later today and let you know just to be sure. Thanks for your help

PLEASE MARK ANY ANSWERS TO HELP OTHERS Blog: rorymon.com Twitter: @Rorymon


Tuesday, September 11, 2012 3:37 AM

I receive an error stating the File can not be found. Any other suggestions? It would be great to get this working. I seem so close!

PLEASE MARK ANY ANSWERS TO HELP OTHERS Blog: rorymon.com Twitter: @Rorymon


Tuesday, September 11, 2012 10:49 AM

Hi Rorymon

That error strikes me as being very strange. Every document must have a template attached. Unless this isn't a *.docx? Is it a *.dotx?

Cindy Meister, VSTO/Word MVP, my blog


Wednesday, September 12, 2012 6:25 AM

Hi Cindy,

I'm using a .dot file. I tried .dotx also before with the same result. Are you saying I should just create a blank word document and try leveraging that?

objDoc = objApp.Documents.Add(AData & "\UAT\ApprovalTemplate.dot")

PLEASE MARK ANY ANSWERS TO HELP OTHERS Blog: rorymon.com Twitter: @Rorymon


Thursday, September 13, 2012 11:36 AM

Hi Rorymon

Mmm, we may be talking at cross-purposes, here...

The line of code you show in your recent response should generate a new document (*.doc) file from the template (*.dot).

This new document should have an active link back to the template - a document cannot exist without a template.

So far, so good. What we cannot see, however, is the string you pass to the SaveAs method to save the new document. By default, I assume the file type is "Word Document *.doc" and that SaveAs is not saving to a template file.

If that is the case, then I'd expect objDoc.AttachedTemplate to point to ApprovalTemplate.dot. HOWEVER...

Just the other day I ran into a similar problem when trying to address files in a folder that my Windows didn't think I had access permissions to. It was System.IO.Packaging, but the error was basically the same - as far as my code was concerned, the file wasn't "there".

As far as I can see, you haven't told us the version of Word or of Windows that's involved, here? I get the impression this is a folder on the Network?

Cindy Meister, VSTO/Word MVP, my blog