Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleCreate a Word document with some formatting in Visual Basic .NET
DescriptionThis example shows how to create a Word document with some formatting in Visual Basic .NET.
KeywordsMicrosoft Word,Word cell format,read from Word,Microsoft Office,Office,Word cell color,cell color,cell format,Word
CategoriesVB.NET, Office
 

A Visual Basic program can open the Word application and use it as a server to manipulate Word documents.

First open the Add References dialog. On the COM tab, select "Microsoft Word 12.0 Object Library" (or whatever version you have installed on your system).

Add the following Imports statement to make working with the Word namespace easier. The "Word =" part means you can use "Word" as an alias for the namespace.

    Imports Word = Microsoft.Office.Interop.Word

This example uses the following code to create a new Word document and add text to it.

 
' Make a Word document.
Private Sub btnGo_Click(ByVal sender As System.Object, ByVal _
    e As System.EventArgs) Handles btnGo.Click
    ' Get the Word application object.
    Dim word_app As Word._Application = New _
        Word.ApplicationClass()

    ' Make Word visible (optional).
    word_app.Visible = True

    ' Create the Word document.
    Dim word_doc As Word._Document = _
        word_app.Documents.Add()

    ' Create a header paragraph.
    Dim para As Word.Paragraph = word_doc.Paragraphs.Add()
    para.Range.Text = "Chrysanthemum Curve"
    para.Range.Style = "Heading 1"
    para.Range.InsertParagraphAfter()

    ' Add more text.
    para.Range.Text = "To make a chrysanthemum curve, use" & _
        "the following " & _
        "parametric equations as t goes from 0 to 21 * ? to" & _
            "generate " & _
        "points and then connect them."
    para.Range.InsertParagraphAfter()

    ' Save the current font and start using Courier New.
    Dim old_font As String = para.Range.Font.Name
    para.Range.Font.Name = "Courier New"

    ' Add the equations.
    para.Range.Text = _
        "  r = 5 * (1 + Sin(11 * t / 5)) -" & vbCrLf & _
        "      4 * Sin(17 * t / 3) ^ 4 *" & vbCrLf & _
        "      Sin(2 * Cos(3 * t) - 28 * t) ^ 8" & vbCrLf & _
            _
        "  x = r * Cos(t)" & vbCrLf & _
        "  y = r * Sin(t)"

    ' Start a new paragraph and then switch back to the
    ' original font.
    para.Range.InsertParagraphAfter()
    para.Range.Font.Name = old_font

    ' Save the document.
    Dim filename As Object = Path.GetFullPath( _
        Path.Combine(Application.StartupPath, "..\\..")) & _
        "\\test.doc"
    word_doc.SaveAs(FileName:=filename)

    ' Close.
    Dim save_changes As Object = False
    word_doc.Close(save_changes)
    word_app.Quit(save_changes)
End Sub
 
The code first creates an instance of the Word.ApplicationClass. Notice that the variable has the odd type Word._Application containing an underscore. (There's also an Application class without the underscore but if you use that then Visual Basic gets a little confused about some ambiguous methods.)

This example makes the Word server visible. In a real application, you might want to keep it hidden.

The Word object model uses lots of method calls that for some reason take object parameters by reference. That means you must put the values for those parameters in variables. For example, you cannot use "True" as a Boolean parameter because you cannot pass a constant by reference. Similarly you can't use a file name such as "C:\wherever\test.doc" for the name of the file you are opening because that is not an assignable variable.

Now the program starts adding text to the document. It adds a Paragraph object to the document's collection.

One of the more important objects in Word is Range. A Range represents a chunk of a document. The code sets the new paragraph's text to "Chrysanthemum Curve." It then sets the Range's style to "Heading 1."

The code then calls the Range's InsertParagraphAfter method. That adds a paragraph mark after the Range's current text and updates the Range so it advances to the new paragraph. Now the Range is ready to add more text after the first paragraph.

The code sets the Range's text again to add the new text and calls InsertParagraphAfter again.

The code will now add some text formatted as code with the font Courier New. It saves the current font's name and sets the Range's font to Courier New. From now on, new text will have this font.

The code sets the Range's text, adds a new paragraph mark, and then restores the original font name so future text will be in the original font.

Next the code calls the Word document's SaveAs method to save the new document. This overwrites any existing file with that name without any warning. If you want to be sure the file doesn't already exist, use File.Exists to check.

Finally the code closes the Word document and the Word application.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated