locked
FAQ: How do I use Word Automation in VB.NET?

Answers

  • Add Reference to COM component “Microsoft Word Object Library” into your project.

    Code sample: Create a new word document, insert a 3 x 5 table and fill it with specific data, finally save it.

     

    Imports Word = Microsoft.Office.Interop.Word
    Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            ' Create Word Application
            Dim oWord As Word.Application = CreateObject("Word.Application")
            ' Create new word document
            Dim oDoc As Word.Document = oWord.Documents.Add()
            oWord.Visible = True
    
            'Insert a 3 x 5 table and fill it with specific data
            Dim r As Integer, c As Integer
            Dim oTable As Word.Table = 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 = "Row" & r & "Col" & c
                Next
            Next
            'make the first row bold and italic
            oTable.Rows.Item(1).Range.Font.Bold = True
            oTable.Rows.Item(1).Range.Font.Italic = True
            ' Save this word document
            oDoc.SaveAs("C:\myfile.doc", True)
            oDoc.Close()
            oWord.Application.Quit()
        End Sub
    End Class
    

    The output in C:\myfile.doc is as follows:


    Row1Col1

    Row1Col2

    Row1Col3

    Row1Col4

    Row1Col5

    Row2Col1

    Row2Col2

    Row2Col3

    Row2Col4

    Row2Col5

    Row3Col1

    Row3Col2

    Row3Col3

    Row3Col4

    Row3Col5


    Related thread:

    http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/6b9bdf3e-aea7-4eb3-a518-56e5108fa202/

     

    KB: How to automate Word from Visual Basic .NET to create a new document
    http://support.microsoft.com/kb/316383/

     

    For more FAQ about Visual Basic .NET General, please see Visual Basic .NET General FAQ



    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Saturday, April 11, 2009 5:55 AM