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 - 06 - Creating Word Documents the Right Way

What are we going to do in this tutorial?

In the previous tutorial, we managed to place text from a textbox in our program in a Word document. However, we encountered a problem: our program does not take into account that one Word instance (the program Microsoft Word) can handle multiple documents at once. Our code does not know that and faithfully opens a new instance of Word each time the program runs the code. These Word instances (visible as 'Winword.exe' in the task manager) interfere with each other and confuse your user. Time to get rid of that problem!

Basically, we are going to teach our program to look for a instance of Word already running. If so, the program will 'catch' that running instance and start working with it. If no instance of Word is running yet, our program will start a new instance. Let's delve into the code.

Step 1

You will continue with the 'MyFirstWordApp' program from the previous tutorial. You are going to change the code that's behind Button 1. The procedure for checking whether Word is running is courtesy of Cindy Meister. Please

Change the code between “Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click” and “End Sub” as follows:

	Dim wdApp As New Word.Application
	Dim appName As String = "Word.Application"
	
	'this code was created by Cindy Meister of Microsoft
	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 wdProcesses.Length > 0 Then
	wdApp = System.Runtime.InteropServices.Marshal.GetActiveObject(appName)
	Else
	wdApp = New Word.Application
	End If
	'end of code from Cindy Meister
	
	'create the Oject 'Word document'
	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
	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

Let's run through the mechanics of the first part of the new code. An object of a Word app is created and the program is told to hold a string called 'Word.Application' in memory. The reason to keep this line in memory is to check whether an instance of Word is already running.

The next few lines of code create the objects 'wdProcesses' and 'wdprocess'. The program checks whether winword is running.

If so, the program is not asked to start a new instance of Word. Instead, our Word program object (wdApp) is attached to the running instance of Word by the 'GetActiveObject' command.

If Winword is not running (the number of processes called 'winword' is zero), your program will start a new instance of Word.

The rest of the program is basically the same as in the previous tutorial.

Step 2

Now that this technical issue has been solved, let's take the program one step further. A Word automation program may have to interact with Word several times at different places in the code. You do not want to copy/paste the procedure each time the program has to interact with Word. Instead, this code will be written once and called upon each time you need it.

Let's get to work.

First, delete all code between “Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click” and “End Sub”. You can switch to this code easily if you click on the button in form1 in the Design view.

Step 3

Now, add a new class to your solution. Right-click the solution in the Solution Explorer and choose Add → Class.

In the next window, choose 'Class' and name the class 'WordActions' and click 'Add'.

Step 4

Place the following code in the new WordActions class (and don't forget to insert the line “Imports Word = Microsoft.Office.Interop.Word” at the top of the class). Place it between the blocks 'Public Class WordActions' and 'End Class'.

Public Shared Function NewWordDoc()
        '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 oWord As Word.Application
        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

This code contains the routine that checks whether an instance of Word is already running. If so, it just creates a new document and if not, a new instance of Word is started and creates a new document. The code is ready for use in our form.

Step 5

Switch back to the code for Form1. Double click the button on this form to go to the code behind the button. Insert the following line.

This code refers to the WordActions class and the procedure (Function) in that class called NewWordDoc. Visual Studio inserts the () automatically.

Now, run the program. When clicking the button on the form, a new Word document is created. Click the button again, and again a new button is created. With the simple command 'NewWordDoc', your program creates a new document while the code to do so is centrally available in the WordActions class. Powerful stuff.

We are going to expand on this in the next tutorial by adding extra code to insert text in a Word document, all this while keeping code centrally located in the WordActions class.

Computing A-Z | Programming | Software


QR Code
QR Code programming_microsoft_word_-_06_-_creating_word_docs_the_right_way (generated for current page)
 

Advertise with Anonymous Ads