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 - 02 - Our first program

Let's get started and write the first program

After the Introduction, it's time for us to write our first program automating Word. We will build a simple Windows form that will take text input and write it in a new Word document at the place of the cursor.

The Word version used is 2007 but it should work with other Word versions as well (older and newer).

If not already done so, Download and install Visual Studio Express for Desktop.

Working with Visual Studio Express

Start Visual Studio. If the program asks you which language you will primarily be working with, chose 'Visual Basic. Soon, you will be looking at the IDE of this program. This may seem a bit overwhelming the first time, but you will know your way around fairly quickly.

You will be working with this IDE a lot, so here is a basic introduction. You are looking at the default look of Visual Studio (VS) right after the start. On top, you find the familiar menu's for opening and closing files, edit, view etc. The rest of the screen is used for window boxes that will help you write your first program.

On the left, there's the 'toolbox'. The toolbox will show all kinds of tools like buttons, textboxes and other stuff that you will need for your program. It works with drag and drop, placing items on the Windows form of your program. In the middle window, you find the tabs on top to switch between files. Most of the coding will be done in this window, so some screen estate will come in handy to fit this between the toolbox on the left and the solution explorer on the right.

The middle window on the bottom will by default be an error list, showing possible errors in your code so you can have an immediate look at it while coding.

Finally, on the right side there is the 'solution explorer' that will show project files like some sort of file browser. We will not be using this in this contribution. On the lower right side, when working on a project you will see a list of properties of a particular selected object. This window allows you to look up and change properties of objects (like the name of a button).

If you feel uncomfortable about is, I recommend that you follow http://www.youtube.com/watch?v=pp5UuZxayCk to get a first feeling of working with the IDE.

Start a new project

Step 1

First, you need to open a new project. Select File → New Project and choose a Visual Basic - Windows and choose 'Windows Form Application' from the options. Give your project a name (like “MyFirstMSWordProgram”) and click 'OK'.

Step 2

Once the project is loaded, we need to make a reference to the Office library. This library basically enables you to 'talk' to Word programmatically and make it do things. This is called 'Interop', a term you will use when writing the code. The program elements to steer Word, must be linked to our project and we will do this with Visual Studio by making a reference to the so-called Office Object Library. For Word 2007 it is version 12 (2003 is 11, 2010 is 13 etc).

The reference is made as follows : (top menu) Project → Add Reference →

Step 3

In the resulting window, choose under the 'COM' element → Microsoft Office 12.0 [or your version of Word] Object Library. The search field as shown below can help you locate this reference easier.

Click OK and you are all set.

Working with some code

Ok, we still need to do one thing before we can program Word. In the IDE's middle window, you find the empty Windows form (a grey rectangle). By default, VS calls this rectangle 'Form1'. Double click the Form1. The IDE will go to the code behind the Form.

In your form, add a reference to the Interop language by means of the following code (place it above the text where the form starts with “Public Class Form1”, see sample below).

Imports Microsoft.Office.Interop.Word

It is possible that this line of code gives you errors. The automatic help for inserting text will not let you choose Interop and/or the error list in the middle window below will start to complain about errors. In that case, make sure that you have installed the so-called Primary Interop Assemblies (PIA) for Word for your Word version. In my example, the PIA for Word 2007 version can be found here.

Designing the GUI of our program

Our program will be steered from the Graphical User Interface (GUI). This is a familiar Windows form on which we will place a textbox and a button. The textbox and button can be dragged with the mouse from the toolbox on the left onto Form1 (see picture below). Drag them around and resize them as fit. We will not change their names in this round.

In the end, your Form1 will look similar to this.

Coding time

Now for some action. Double click the button you just dragged onto Form1. The IDE will show you the code behind that button and places the cursor ready to insert some code. Alternatively, you can switch to the code behind Form1 by right-clicking 'Form1' in the Solution Explorer (see picture), but then you will have to go to the block that holds the code for the button yourself.

You will be inserting the following code on that exact spot:

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

Try
wdDoc  = wdApp.Documents.Add()
wdApp.Visible = True
Catch ex As Exception
MsgBox("Error creating Word document.")
End Try

wdApp.ActiveWindow.Selection.TypeText(TextBox1.Text)

wdApp = Nothing

When done, it will look like this:

We will go through this code step by step explaining what it does, but first let's run the program!

Running the program

The button 'Start' will build our program and subsequently run it as a regular Windows program. VS will not let you run the program if there are still errors in the code.

The program is running successfully. In the example above, I inserted some text in the textbox. Write some text in the textbox yourself and press the button.

Voila, the end result. The program has opened a new Word document and inserted the text from the textbox in the Word document at the place of the cursor (=start of Word document). Your first manipulation of Word by means of a software program…

How does this code work?

Below, we will go through the code in more detail but first the warning that his code is not suitable yet for our purposes. You will notice that - if you had Word already running - a second version of Word was started that will conflict with the earlier running version. If you close the newly created document and close the 2nd version of Word running, it will complain about another version of Word running. Close Word but do not overwrite the normal.dot file. We will fix this behaviour in future contributions.

Now the code.

1. With the 'Dim' command, we make sure that the program knows that there will be a Word object (Word.Application → the Word software) and a Word document object (Word.Document → a Word document).

2. The code 'try, catch and End try' is inserted to perform some basic error handling. If an error would occur when executing the code and no error handling is provided, our program would crash. Now, an error would trigger a message box indicating something went wrong. Proper error handling is very important when writing software.

3. the command 'wdDoc = wdApp.Documents.Add()' basically starts Word (whether already running or not) and opens the default blank document. With 'wdApp.Visible = True', we make sure that Word will be visible on screen.

4. The command to type text into a Word document at the place of the cursor is 'wdApp.ActiveWindow.Selection.TypeText(TextBox1.Text)'. Behind TypeText we could have added text between ”” ourselves, but instead, we point the program to the contents '.Text' of our textbox (which by default is named 'TextBox1').

5. the object wdApp is made 'nothing' again as clean up afterwards.

Next contribution: step by step

The next contribution deals with the GUI. We will create a little program that hides in the Windows tray and will show a menu when right-clicked with the mouse. This menu will hold all our future Word actions, so that we will have Word automation ready at our fingertips when needed.

Next contribution (part 3)

Computing | Programming | Software


QR Code
QR Code programming_microsoft_word_-_02_-_our_first_program (generated for current page)
 

Advertise with Anonymous Ads