Tuesday, March 2, 2010

How to Create a Word Document in Visual Basic

Visual Basic is a programming language designed and manufactured by Microsoft. Visual Basic is one of the most popular programming languages used by both novices and experts. VB can reference objects from other applications such as Microsoft Word to increase the breadth of programming capabilities. Creating a Word document from a Visual Basic application allows a professional document to be produced from the application with minimal effort for the developer. Billing, invoices, time sheets and reports are examples of documents often created from Visual Basic applications.

Instructions

Things You'll Need:

  • Visual Basic
  • Microsoft Word
  1. Step 1

    Open the Visual Basic application and create a new project using the "Ctrl" and "N" keys. Select the template labeled "Windows Forms Application."

  2. Step 2

    Select "Project" from the menu bar, then select the "References" option. Check the item "Microsoft Word object library" and then click the "OK" button to continue.

  3. Step 3

    Create a button labeled "ButtonOne" on the form.

  4. Step 4

    Double click on "ButtonOne" to open the code window. Insert the following code below the line "Private Sub ButtonOne_Click":

    Dim oWord As Word.Application
    Dim oDoc As Word.Document
    Dim oRng As Word.Range

    'Start Word and open the document template.
    oWord = CreateObject("Word.Application")
    oWord.Visible = True
    oDoc = oWord.Documents.Add
    oRng = oDoc.Bookmarks.Item("\endofdoc").Range
    oRng.InsertAfter("This is the new document you created.")

    Me.Close()

  5. Step 5

    Insert the following code at the top of the code for "Form1":

    Imports Word = Microsoft.Office.Interop.Word

  6. Step 6

    Execute the code in debug mode using the "F5" key.

  7. Step 7

    Click on the button labeled "ButtonOne" to execute the code. A Microsoft Word document will be displayed in a new window with the text "This is the new document you created."

No comments:

Post a Comment