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 - 07 - Reusing Your Code

What are we going to do in this tutorial?

In the previous tutorial, we took away the problem of more than one instance of Word running while running your code over and over again. The routine to avoid this from happening is fairly complex and long. In this new tutorial we are going to break up the code some more, so the block of code to open a new Word document can be reused multiple times.

We are going to build on top of the 'MyFirstWordApp' from tutorial 5 that was enhanced in tutorial. If you do not have this project available, please go through the previous two tutorials to create that program.

Step 1

Open the 'MyFirstWordApp' program as you left it in the previous tutorial: File → Open Project → [choose relevant .sln file]

Step 2

The design of Form1 will remain the same.

However, we are going to change the code behind 'Button1'. First, we are going to add a new class to our project. In the Solution Explorer, right-click the project and move through the menu that appears: Add → Class

Name the new class 'Wordactions.vb'.

Step 3

If your new class is not shown yet in the code editor, double click the new WordActions class in the Solution Explorer. First, insert a reference to Word Interop.

Second, create a Function called 'NewWordDoc' by inserting the following code between 'Public Class WordActions' and 'End Class'.

Public Shared Function NewWordDoc(oWord As Word.Application) As Word.Application
        'Procedure NewWordDoc()
        '
        '1. check whether Word is running
        '2. if so, open a new document
        '3. if not, start word and open new document
        '
        'Code to check whether Word is running
        'courtesy of Cindy Meister, VSTO/Word MVP

        Dim oDoc As Word.Document
        Dim appName As String = "Word.Application"
        Dim wdProcesses() As System.Diagnostics.Process = _
          System.Diagnostics.Process.GetProcessesByName("winword")
        Dim wdprocess As System.Diagnostics.Process

        For Each wdprocess In wdProcesses
            System.Diagnostics.Debug.Print(wdprocess.MainWindowTitle)
            System.Diagnostics.Debug.Print(wdprocess.StartInfo.Arguments.Length.ToString())
        Next

        'If Word is running, attach oWord to that instance of Word
        If wdProcesses.Length > 0 Then
            oWord = System.Runtime.InteropServices.Marshal.GetActiveObject(appName)

            'if Word is not running, start new instance of Word
        Else
            oWord = New Word.Application
        End If

        If Not oWord Is Nothing Then
            oWord.Visible = True
            oWord.Activate()

        End If

        oWord.Visible = True

        'open new Word document based on the basic template
        oDoc = oWord.Documents.Add

        'Don't know what it does but by doing so, I 
        'avoid a warning in Visual Studio about possibly
        'no returning a value on all code paths
        Return oWord

        oDoc = Nothing
        oWord = Nothing


    End Function

There are a couple of things different in this code than in the code from tutorial 6. We will run through this later in this tutorial to show the differences.

Third, insert another block of code between 'Public Class WordActions' and 'End Class' (I suggest placing it below the NewWordDoc function just created).

This WordActions class contains code that we can reuse over and over again in our project. This saves time and avoids unnecessary bugs. Furthermore, updating code becomes easier. Now, we will look at the code behind 'Button1'.

Step 4

Double click on the Button1 in Form1 in the design view.

Now, please update the code between 'Private Sub Button1_Click …' and 'End Sub' to read like this:

Now, test your application by running it, placing text in the textbox and hitting Button1.

And it is working fine:

In the paragraphs below, we will run through this new code to get a better idea how the code works.

Reviewing the code closer

Let's take a closer look at what happens when the user clicks the button. My explanation is not very technical. I just try to make some sense in what's happening so you get a basic understanding of what the code does. It all starts in Form1.

First, there are to objects declared: oWord as Word application and Sel as Word selection. This is done because we need those two objects later on in the code.

Second, the text in the textbox1 on our form is placed in the variable 'iNsert'. After these variables have been declared, the command NewWordDoc is called. There are a few things happening here.

1. the oWord variable is redefined as the 'outcome' or 'result' of the Function 'NewWordDoc'. Because this function is located in the class 'Wordactions', it is typed as 'WordActions.NewWordDoc'.

2. The addition of (oWord) at the end feeds the oWord object created in Form 1 to the NewWordDoc function in the class WordActions.

When looking at the code for the function 'NewWordDoc' in the class 'WordActions', you will notice that the first line contains a few particular elements.

Public Shared Function NewWordDoc(oWord As Word.Application) As Word.Application

'Public' and 'Shared' mean that this code is accessible and can be used in a certain way in your program, not only within the WordActions class itself. The Function description contains some additional input between the brackets. What we are telling the computer is that it should expect a Word Application object to be feeded into the function. In our case we feed it with 'oWord' created in the Form1 code.

The code after the brackets 'As Word.Application' is used to have this function return a Word application object. We pass this back to the Form1 code with the 'return oWord' command later in the 'NewWordDoc' code. We do this because we need that oWord object in the next steps in Form1. The Word document created was created in the NewWordDoc function. To make this Word object - in the context of the NewWordDoc code attached to the actual Word application running - also accessible to the code in Form1, the funciton returns this Word object (oWord) to the code in Form1. This may look confusing (and the computer being dumb), but this is a very essential element to make this code work. Please look at this concept closely and try to understand what is happening.

After the NewWordDoc function has created a new Word document, the next line in the Form1 code gives the computer the assignment to place the text, held in the variable 'iNsert' (a string) into the Word document just opened. Lets take a closer look at this code in Form1.

Sel = oWord.Selection

Remember, we declared an object being a Word.Selection. Now, the selction (Sel) is set equal to the selection in the oWord object which came out of the NewWordDoc function. Basically, this is the start of the newly created Word document. This enables the code to insert text at the cursor in the Word document. We look at this in closer detail in our review of the next line of code.

WordActions.TypeText(iNsert, Sel)

Again, in the Form1 code reference is made to a command in the WordActions class. This time the 'TypeText' command is called. The TypeText command is completed with two elements between brackets. We feed this command with iNsert (a string) and the selection in the Word document (basically the place of the cursor).

Public Shared Sub TypeText(ByVal text As String, ByRef Sel As Word.Selection)
Sel.Text = text
Sel.Start = Sel.End

Again, we see the 'Public' and 'Shared' attributes to a command. Because this command (also called a procedure) does not return anything, it is called a 'Sub' instead of a 'Function'. The Sub 'TypeText' has two parameters between the brackets: 1. 'text' as a string (the line of text that we want typed in our document) and 2. 'Sel' as a word selection (the place of the cursor in the Word document). Subsequently, the command 'Sel.Text = text' is the actual command placing the text in the Word document. The next line 'Sel.Start = Sel.End' is used to make sure that the cursor in the actual Word document is set just after the last character our program placed in the word document. This is handy if we have additional lines of code inserting additional lines of text in the Word document.

There is an easier way of typing text in the Word document created. Instead of the route via our WordActions.TypeText routine. you could also use the following code to insert text. Place this code in the Sub 'TypeText' in the WordActions class and see whether it works.

Sel.TypeText(text)

We could also insert this code in the Form1 code directly (change 'text' to 'iNsert' then), but that would defeat the purpose of showing reusing code in this tutorial :)

This concludes this tutorial on reusing code. In the next tutorial, we will expand on reusing code a little bit.

Computing A-Z | Programming | Software


QR Code
QR Code programming_microsoft_word_-_07_-_reusing_your_code (generated for current page)
 

Advertise with Anonymous Ads