DEVTOME.COM HOSTING COSTS HAVE BEGUN TO EXCEED 115$ MONTHLY. THE ADMINISTRATION IS NO LONGER ABLE TO HANDLE THE COST WITHOUT ASSISTANCE DUE TO THE RISING COST. THIS HAS BEEN OCCURRING FOR ALMOST A YEAR, BUT WE HAVE BEEN HANDLING IT FROM OUR OWN POCKETS. HOWEVER, WITH LITERALLY NO DONATIONS FOR THE PAST 2+ YEARS IT HAS DEPLETED THE BUDGET IN SHORT ORDER WITH THE INCREASE IN ACTIVITY ON THE SITE IN THE PAST 6 MONTHS. OUR CPU USAGE HAS BECOME TOO HIGH TO REMAIN ON A REASONABLE COSTING PLAN THAT WE COULD MAINTAIN. IF YOU WOULD LIKE TO SUPPORT THE DEVTOME PROJECT AND KEEP THE SITE UP/ALIVE PLEASE DONATE (EVEN IF ITS A SATOSHI) TO OUR DEVCOIN 1M4PCuMXvpWX6LHPkBEf3LJ2z1boZv4EQa OR OUR BTC WALLET 16eqEcqfw4zHUh2znvMcmRzGVwCn7CJLxR TO ALLOW US TO AFFORD THE HOSTING.

THE DEVCOIN AND DEVTOME PROJECTS ARE BOTH VERY IMPORTANT TO THE COMMUNITY. PLEASE CONTRIBUTE TO ITS FURTHER SUCCESS FOR ANOTHER 5 OR MORE YEARS!

Programming Microsoft Word - 05 - From Form to Word Document (II)

What are we going to do in this tutorial?

In the previous tutorial, we managed to take the tray application from tutorial 3, expand on it by building a second windows form and use textboxes on that new form to capture input from a user. The purpose of this tutorial is to direct this input to a Word document instead of the message box of the previous tutorial.

Because the interaction between your program and Windows Word requires some background information, I decided to dedicate a separate tutorial to the magic behind all this. Once you get this up and running, it's easy, but for future ease of use is vital to understand the basics behind it. I assume you have a copy of Office (2003 or upwards) installed on your PC.

Step 1

Before we go on with the program from the previous tutorial, you are first going to create a new project called 'MyFirstWordApp'. To do so, start Visual Studio and go to: File → New Project and choose Windows Forms Application. Set the name of the project to 'MyFirstWordApp'. Moving forward quickly, place a textbox on the form and a button. Your screen will look like this:

Step 2

Before we add code, we need to make our program aware of the programming language necessary to manipulate Word documents. We will do so now.

In the top menu of Visual Studio, go to: Project → Add Reference

In the 'Reference Manager' window that pops up, we are looking for the COM list. Click the COM element on the left and a large list of references appears. We are looking for the 'Microsoft Office 12.0 Object Library'. The version number 12.0 indicates that I am using Office 2007. Other versions of Office will render other version numbers for the relevant library (For instance, Office 2003 is 11.0). Just choose the version that is offered in your case.

Finding this library is easier by looking it up through the search window at the top-right (see picture below). Click and select 'Microsoft Office 12.0 Object Library' (or your version of this Object library.

We want to add reference to another library: the 'Microsoft Word 12.0 Object Library'. Again, the version shown in your window may be different, depending on your Office version. Select the 'Microsoft Word 12.0 Object Library' and click OK.

Adding reference is not visible in your code. However, it is a vital step to ensure that your program can 'talk' to Word. We are going to insert another reference, but now in our code. In the top of the form's code (so not the design view but the code behind the form), above the line 'Public Class Form1', insert the following code:

	Imports Word = Microsoft.Office.Interop.Word

You will find out later on that this enables a reference to the Word object model through the statement 'Word' in your code.

Step 3

Now it is time to start with some real coding. In the design view, double click on the button; Visual Studio will bring your cursor between the lines 'Private Sub Button1_Click' and 'End Sub'.

Enter the following code:

	Dim wdApp As New Word.Application
        Dim wdDoc As Word.Document

        'This code will start Word and open a new document
        'from the standard template. If an error occurs, the program
        'throws a message
        Try
            wdDoc = wdApp.Documents.Add()
            wdApp.Visible = True
        Catch ex As Exception
            MsgBox("Error creating Word document.")
        End Try

        'With this line of code, the text in the textbox will be inserted
        'at the place of the cursor in word
        wdApp.ActiveWindow.Selection.TypeText(TextBox1.Text)

        'cleaning up
        wdApp = Nothing

This code starts with declaring two variables that will deal with two objects: the Microsoft Word program itself and a Microsoft Word document (the lines starting with 'Dim'). By doing so, your program has an object to work with (either a Word document or Word itself).

Second, the code declares a Word Document (wdDoc) and ask to 'Add' a document (wdApp.Documents.Add() ). To make sure that the Word application is visible to the user, the wdApp.Visible is set to true. This block of code is placed between a Try… Catch ex … End Try construction. This is done to avoid the program crashing if the user has no Microsoft Word installed. The 'Exception' will then lead to a message box appearing with an error notice.

Then the actual code to write text in a Word document. The program has already opened Microsoft Word and opened a blank document. The line 'wdApp.ActiveWindow.Selection.TypeText' tells the program a couple of things. ActiveWindow is the window active when the code runs. Selection is basically the place were the cursor is; in our case the start of a blank Word document. Then the command that actually 'types' text. Hence 'TypeText'. The text to be typed is taken from the Textbox1 (Textbox1.Text in the code).

The final line of code is about cleaning up. The object wdApp is set to nothing.

Now, run the program, type some text in the textbox and hit that button. Voila, your text appears in a blank Word document

A problem appears

Keep the program running and try another line. And then insert a third line of text and hit that button again. You will have three Word documents open, showing the lines you just inserted in your program one by one.

However, there is a problem hidden in the dark. Each time your program 'adds' a Word document, it opens a new instance of Word. Consequently, you now have 3 instances of Microsoft Word running. Start the task manager via Ctrl-Alt-Del and look at the programs running. You will find three Word programs (Winword.exe) running instead of one (see picture).

Your user will find out that there is a problem when he closes a Word instance. Because there are more than one Word instances running, these instances will interfere with each other and render akward error notices.

Word is capable of opening multiple documents within one instance of the Word program running. We have to fix our code to check whether an instance of Word is already running before opening a new instance. We are going to to this in the next tutorial.

Computing A-Z | Programming | Software


QR Code
QR Code programming_microsoft_word_-_05_-_from_form_to_word_document_ii (generated for current page)
 

Advertise with Anonymous Ads