Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

434 Chapter 10 AUTOMATING MICROSOFT OFFICE APPLICATIONS

also access the spell-checking features of Word with a text document generated with VB.NET. Or you can create spreadsheets from within a VB application, complete with formulas. Then you can retrieve the results and use them in your VB application. All this can happen with Excel running in the background, and the users never see it. You can literally borrow the functionality of the Office applications and use it in your VB projects.

Of course, the object models of the Office applications aren’t part of Visual Studio. They will be available to program against only if you have installed a version of Office on your system. The object models of the various versions of Office are very similar, and you should be able to adjust the code to accommodate syntactical changes. The samples of this chapter were developed with Office 2000 and they may require some minor changes to work with Office XP.

This chapter doesn’t attempt to present the object models of the corresponding applications in their entirety. It’s only an introduction to the topic of automating the Office applications by programming their objects. VBA programmers are already familiar with the object models discussed in this chapter, and they’ll leverage their skills by bringing their knowledge of Office to Visual Basic. VB programmers, on the other hand, will learn how to program the object model of an external application and extend VB. They will also have to learn the object model of the application they’re programming against, and the information in this chapter is more than adequate to get you started.

Programming Word

Word is a top-notch word processor, and you can tap into the power of Word through the object model it exposes. You can create documents, format them, and store them as DOC files. You can print these files, or e-mail them as attachments to a list of addresses. You can also reuse Word’s spell-checking capabilities to correct documents at runtime. You will see later in this section how to spell-check a text document with a few lines of code using the objects exposed by Word.

Microsoft Word provides numerous objects, which you can use to program any action that can be carried out with menu commands. For example, you can open a document, count words and characters, replace certain words in it, and save it back on disk without user intervention. You can actually do all this without displaying Word’s window on the Desktop.

The top-level Word object is the Application object, which represents the current instance of the application. You can use the Application object to access some general properties of Word’s window, including its Visible property (to make the application visible or not). Normally, this property should be False, but you can turn it on during debugging to see what each statement in your code does to the current document.

To use the object model of Microsoft Word in your VB project, you must add a reference to the Microsoft Word application to the project. Open the Project menu, select Add References and, on the Add Reference dialog box, select the COM tab. Then locate the Microsoft Word 9.0 Object Library item by double-clicking its name and click OK to close the dialog box. (This version number applies to Office 2000. By the time you’re reading this book, you may be using a newer version of Office. Select the Word component with the highest version number in the list.)

To program against Word’s objects, you must first create a variable that represents the application, with a statement like the following:

Dim WordApp As New Word.Application

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

PROGRAMMING WORD 435

The New keyword tells VB to create a new instance of Word. This will start Word, but no visible interface will be displayed on the monitor. The WordApp variable must be declared on the Form level, so that all procedures can access it.

Under the Application object is the Documents collection, which contains a Document object for each open document. Using an object variable of the Document type, you can open an existing document or create a new document. The following statement opens an existing document with a specific name (assuming the specified document exists on the drive):

doc1 = WordApp.Documents.Open(“My Word Samples.doc”)

To create a new document, call the Add method of the Documents collection and then save the new document with the SaveAs method:

Dim newDoc As New Word.Document newDoc = WordApp.Documents.Add newDoc.SaveAs(“My new Document”)

The first statement declares a new document, and the second one adds a new document to the current instance of Word. After the execution of these statements, you can insert text, format it, and do anything you can do with the active document through Word’s interface.

If you don’t specify a path name, the document is saved in the default Save folder of Word. The SaveAs method accepts many more arguments, which are discussed in the section “Printing and Saving Documents,” later in this chapter.

If the document has been saved already, you can call the Save method, which requires no arguments. Lastly, you must close the document and quit the application. The following statement closes the active document:

Documents.Close(saveChanges, originalFormat, routeDocument)

All three arguments are optional. The saveChanges argument is a member of the WDSaveOptions enumeration and can have one of the following values: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges. The originalFormat argument determines the format that will be used to save the document; its value is a member of the WDOriginalFormat enumeration: wdOriginalDocumentFormat, wdPromptUser, or wdWordDocument. The last argument is a True/False value indicating whether the document should be routed to the next recipient. If the document doesn’t have a routing slip attached, this argument is ignored.

If you have multiple open documents at once, you can select the active document with the ActiveDocument property. This property returns a Document object, and you can call it as shown here:

doc1 = WordApp.ActiveDocument

If the variable doc1 represents an open document, you can make it the active document by calling the Activate method:

doc1.Activate

You can also create a new document by adding it to the Documents collection:

Dim doc As New Word.Document doc = WordApp.Documents.Add

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

436 Chapter 10 AUTOMATING MICROSOFT OFFICE APPLICATIONS

After you’re done processing the document, you can save it by calling the SaveAs method, with the following statement:

Documents.SaveAs(fileName)

where fileName is a user-supplied filename (you can display the SaveFile common dialog to prompt the user for the file’s name).

If the document has been modified since it was last saved, you must set the argument saveChanges to wdDoNotSaveChanges or wdSaveChanges. If you omit to close a changed document, the application won’t terminate and, when you shut down your computer, you’ll be prompted as to whether you want to save the file.

Note If your application crashes, the next time you start Word you may see a bunch of recovered documents. These documents are leftovers of (rather unsuccessful) testing and debugging attempts.

To terminate the application, call its Quit method, and then set the WordApp variable to Nothing. If you omit these steps and simply terminate your VB project, the instance of Word running in the background won’t shut down. Every time you instantiate a variable to represent Microsoft Word, a new instance of the application will start and will remain alive in memory until you shut down the computer. Make sure you program the Closing event of your application, so that you won’t leave any instances of Word floating around. The Closing event handler should contain the following lines:

Private Sub Form1_Closing(ByVal sender As Object, _

ByVal e As System.ComponentModel.CancelEventArgs) _

Handles MyBase.Closing

WordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

WordApp.Quit()

WordApp = Nothing

End Sub

The Close method of the Documents collection closes all open documents without saving them. Then the Quit statement terminates Word. This code segment assumes that the documents have been saved already. If not, it will simply close them without prompting, which means you may lose the edits.

Note While you’re testing an application that uses any of the Office object models, you may have to end the application before it has had a chance to terminate the Office application. To find out if there are any instances of Word running in the background, invoke the Task Manager window by pressing Ctrl+Alt+Delete. On the Task Manager window, select the Processes tab and look for instances of the Office application you’re programming against. The names of the three Office applications are WINWORD, EXCEL, and OUTLOOK, and if they appear in the list of processes while your application isn’t running, you must terminate them manually. If you see too many instances of an Office application in the processes list, it means that your application doesn’t terminate the Office application properly.

Tip If you stop the VB project by clicking the Stop button (or by selecting Debug Stop Debugging), the Closing event won’t be triggered. While testing a project that contacts an Office application, try to terminate it with the End statement, or by clicking the Form’s Close button. If you must terminate the application prematurely because of an error, open the Task Manager and shut down manually the running instances of the Office application.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

PROGRAMMING WORD 437

Objects That Represent Text

The most important object that each document exposes is the Range object, which represents a contiguous section of text. This section can be words, part of a word, characters, or even the entire document. Using the Range object’s methods, you can insert new text, format existing text (or delete it), and so on. You can also use the Selection object to access part of the document. Both the Range and Selection objects will be discussed later in this chapter in detail.

To address specific units of text, use the following collections:

The Paragraphs collection, which is made up of Paragraph objects that represent text paragraphs

The Words collection, which is made up of Word objects that represent words

The Characters collection, which is made up of Character objects that represent individual characters

The Documents Collection and the Document Object

The first object under the Word Application object hierarchy is the Document object, which is any document that can be opened with Word or any document that can be displayed in Word’s window. All open documents belong to a Documents collection that is made up of Document objects. Like all other collections, it supports the Count property (the number of open documents); the Add method, which adds a new document; and the Remove method, which closes an existing one. To access an open document, you can use the Item method of the Documents collection, specifying the document’s index as follows:

Application.Documents.Item(1)

Or you can specify the document’s name:

Application.Documents.Item(“Chapter01.doc”)

To open an existing document, use the Documents collection’s Open method, whose syntax is:

Documents.Open(fileName)

The fileName argument is the document file’s path name. To create a new document, use the Documents collection’s Add method, which accepts two optional arguments:

Documents.Add(template, newTemplate)

The argument template specifies the name of a template file to be used as the basis for the new document. The newTemplate argument is a Boolean value. If it’s set to True, Word creates a new template file.

Most of the operations you’ll perform apply to the active document (the document in the active Word window), which is represented by the ActiveDocument object, a property of the Application object. To access the selected text in the active document, use the following expression:

Application.ActiveDocument.Selection

You can also make any document active by calling the Activate method of the Document object. To make the document MyNotes.doc active, use the following statement:

Documents(“MyNotes.doc”).Activate

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

438 Chapter 10 AUTOMATING MICROSOFT OFFICE APPLICATIONS

You can also pass the index of a document as argument to the Documents collection to specify one of the open documents. After the execution of this statement, the MyNotes.doc document becomes the active one, and your code can refer to it through the object Application.ActiveDocument.

To access the first word in the active document use the following expression, which returns a Word object:

WordApp.ActiveDocument.Words(1)

The Word document exposes several properties, one of them being the Text property, which returns a string (the first word in the document):

WordApp.ActiveDocument.Words(1).Text

You can go through all the words in the active document with a loop like the following:

Dim word As Word.Range

For Each word In WordApp.ActiveDocument.Words

Console.WriteLine(word.Text)

Next

Notice that there’s no object that represents a word; a word is simply a Range object—the Words collection contains a Range object for each word in the document.

The following loop goes through the paragraphs of the active document, converts them to Range objects, and then prints the paragraph’s text through the Range.Text property:

Dim para As Word.Paragraph

For Each para In WordApp.ActiveDocument.Paragraphs

Console.WriteLine(para.Range.Text

Next

Printing and Saving Documents

To print a document, call its Printout method, which has the following syntax:

Printout background, append, range, outputfilename, from, to, item, copies, _ pages, pageType, PrintToFile, Collate, filename, ActivePrinterMacGX, _ ManualDuplexPrint, PrintZoomColumn, PrintZoomRow, _ PrintZoomPaperWidth, PrintZoomPaperHeight

All the arguments are optional; they correspond to the properties you can set on Word’s Print dialog box. The background argument is a True/False value that specifies whether the printout

will take place in the background, and this argument is usually set to True when we’re automating applications.

When calling methods with a large number of arguments (most of which are omitted anyway), you should use named arguments to specify only a few arguments. For example, to print the first three pages of the active document, use the following syntax:

AppWord.ActiveDocument.Printout from:=1, to:=3

To save a document, use the SaveAs method of the Document object, which has the following syntax:

SaveAs FileName, FileFormat, LockComments, Password, AddToRecentFiles, _

WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, _

SaveNativePictureFormat, SaveFormsData, SaveAsOCELetter

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

PROGRAMMING WORD 439

As with the Print method, the arguments of the SaveAs method correspond to the settings of the application’s Save As dialog box. If the file has been saved already, use the Save method, which accepts no arguments at all. It saves the document to its file on disk using the options you specified in the SaveAs method when the document was saved for the first time. To save the active document under a different filename, use the following statement:

AppWord.ActiveDocument.SaveAs “c:\Documents\Report2002.doc”

Notice that there’s no argument for overwriting an existing file. If you attempt to overwrite an existing file, a dialog box will pop up prompting you for whether you want to overwrite the file or cancel the operation. If you don’t want your user to see any of Word’s dialog boxes, you must make sure the file doesn’t exist from within your code (or delete the file).

A related property of the Document object is the Saved property, which returns a True/False value indicating whether a document has been changed since the last time it was saved. Use the Saved property in your code to find out whether you must call the Save method before you quit the application.

The code segment in Listing 10.1 creates a new document, prints it, and then quits without saving it. The WordApp variable is declared outside the procedure, because it will most likely be used by other procedures in the same application. Notice that you can call the Add method of the Documents collection without a filename. The new document is called Document1, but it’s not saved on disk.

Listing 10.1: Creating and Printing a DOC File

Dim WordApp As New Word.Application()

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click Dim thisDoc As New Word.Document()

thisDoc = WordApp.Documents.Add With thisDoc

.Range.InsertAfter(“Printing with Word”)

.Paragraphs.Item(1).Range.Font.Bold = True

.Paragraphs.Item(1).Range.Font.Size = 14

.Range.InsertParagraphAfter()

.Paragraphs.Item(2).Range.Font.Bold = False

.Paragraphs.Item(2).Range.Font.Size = 12

.Range.InsertAfter(“This is the first line of the test printout”)

.Range.InsertParagraphAfter()

.Range.InsertAfter(“and this is the second line of the test printout”) Try

.PrintOut(True, True) Catch exc As Exception

MsgBox(exc.Message) End Try

.Close(Word.WdSaveOptions.wdDoNotSaveChanges) End With

WordApp.Quit() End Sub

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

440 Chapter 10 AUTOMATING MICROSOFT OFFICE APPLICATIONS

The sample code calls the PrintOut method of the Document object to print the current document. The two parameters passed to the method correspond to the background and append arguments. If something goes wrong during printing, the structured error handler will catch the exception and report it on a message box. The body of the procedure generates a sample document (you will see in the following section how the Range object can be used to create a new document).

Manipulating Text

As mentioned already, the two basic objects for accessing text in a Word document are the Range and Selection objects. The Selection object represents a contiguous segment of text, similar to making a selection with the mouse. The Range object is a also a collection of characters, words, or paragraphs, similar to the Selection. The difference between the two objects is that there’s only one Selection object in a document, but you can define many Range objects. You can manipulate individual Range objects without affecting the current selection.

To extract some text from a document, you can use the Document object’s Range method, which accepts as arguments the positions of the starting and ending characters in the text. The syntax of the Range method is:

Document1.Range(start, end)

where Document1 is a variable of the Word.Document type and represents a Word document. The start and end arguments are two numeric values. The first character’s position in the document is 0. The following statement extracts the first 100 characters of the document represented by the Document object variable:

Range1 = Document1.Range(0, 99)

These characters are assigned to the Range1 object variable. The Range1 variable must be declared as Range type:

Dim Range1 As Word.Range

In the preceding expressions, the Document1 variable must first be set to refer to an existing object with statements like

Dim Document1 As Word.Document = WordApp.Documents.Item(1)

You can also replace the variable Document1 with the built-in object ActiveDocument, which represents the active document. The selected text in the active document can be accessed by the following expression:

WordApp.ActiveDocument.Selection

Words, sentences, and paragraphs are more meaningful units of text than characters. The Word, Sentence, and Paragraph objects are better suited for text manipulation, and you commonly use these objects to access documents. These objects, however, don’t support all the properties of the Range object. All units of text can be converted to a Range object with the Range property. For example, the following statement returns the third paragraph in the specified document as a Range object:

Document1.Paragraphs(3).Range

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

PROGRAMMING WORD 441

You can then apply the Range object’s properties and methods to manipulate the third paragraph. The Paragraph object doesn’t have a Font property or a Select method. To change the appearance

of the third paragraph in the document, you must first convert the paragraph to a Range object with a statement like this:

Set Range1 = Document1.Paragraphs(3).Range

Range1.Font.Bold = True

Document1 is a properly declared Document variable, and Range1 is a properly declared Range variable. You can also combine both statements into one and avoid the creation of the Range1 object variable as follows:

Document1.Paragraphs(3).Range.Font.Bold = True

The following statement selects (highlights) the same paragraph:

Document1.Paragraphs(3).Range.Select

(You won’t see the selection, of course, but if you make Word’s window visible at this point, you’ll see that the Select method actually highlights a section of the document.) Once a paragraph (or any other piece of text) is selected, you can apply all types of processing to it (e.g., edit it, move it, format it).

The two methods of the Range object that you’ll use most often are InsertAfter, which inserts a string of text after the specified Range, and InsertBefore, which inserts a string of text ahead of the specified Range. The following statements insert a title at the beginning of the document and a closing paragraph at the end:

AppWord.ActiveDocument.Select

AppWord.ActiveDocument.Range.InsertBefore “This is the document’s title” AppWord.ActiveDocument.Range.InsertAfter “This is the closing paragraph”

The Select method of the ActiveDocument object selects the entire text. The selected text is then converted to a Range object, so that the Range object’s methods can be applied to it.

To create a new paragraph, use InsertParagraphBefore and InsertParagraphAfter. Both methods will insert a new paragraph, before or after the specified range.

The Current Selection

The Selection object represents the current selection in the active document. This property returns the range of text selected by the user, but you can also select a range of text from within your application. The Selection object is very similar to the Range object, and both objects expose the same functionality. Although you can maintain many Range objects in your application, there’s only one selection. When the current selection is changed, the previous selection is lost.

Note Selection is a property of the Application object and represents the selected text in the current document (the active document). If no text is selected, the Selection object represents an empty range of text. Its location is the same as the location of the insertion point.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

442 Chapter 10 AUTOMATING MICROSOFT OFFICE APPLICATIONS

Accessing Paragraphs, Words, and Characters

While all collections in Word are 1-based, the Characters collection is 0-based. To access the first document in the Documents collection, we use an index value of 1. To access the first sentence in the document, we also use an index of 1, and the same is true for the first word. The first character, however, has an index of 0.

Let’s say you have added a document to the Documents collection, represented by the doc variable:

Dim doc As New Word.Document() doc = W.Documents.Add

W represents a running instance of Word, and it’s declared on the Form level. Add two lines of text to the document with the following statements:

doc.Range.InsertAfter(“The quick brown fox “) doc.Range.InsertParagraphAfter() doc.Range.InsertAfter(“jumped over the lazy dog”)

Let’s experiment with extracting paragraphs, words, and characters from the current document. To read the first five characters of the document, enter the following statement:

Console.WriteLine(doc.Range(0, 5).Text)

This statement will print the string “The q” on the Output window (without the quotes, of course). To read the first paragraph, we must request the first member of the Paragraphs collection and get its Range property. Then we’ll apply the Text property to read the text:

Console.WriteLine(doc.Range.Paragraphs.Item(1).Range.Text)

This statement will print the string “The quick brown fox ” on the Output window. Finally, you can read the second word with the following statement:

Console.WriteLine(doc.Range.Paragraphs.Item(1).Range.Words.Item(2).Text)

The second word is “quick,” which indicates that the Words collection is 1-based, like the Paragraphs collection.

Note that the Paragraph object must be converted to a Range object before you can access its Words collection.

To specify a Selection, use the Start and End properties, which are the locations of the starting and ending character of the selection in the document. If you set both properties to the same value, you’re in effect positioning the insertion pointer to the specified location. The following statements select three characters, starting with the eleventh character in the document, and print them on the Output window:

WordApp.Selection.Start = 10

WordApp.Selection.End = 12

Console.WriteLine(WordApp.Selection.Text())

The Start and End properties are expressed in characters, and as such they’re 0-based. The Selection.Type property returns information about the current selection, and its value can be one

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

PROGRAMMING WORD 443

of the members of the WDSelectionType enumeration: wdNoSelection, wdSelectionBlock, wdColumn,

wdFrame, wdInLineShape, wdIP, wdNormal, wdRow, and wdShape. IP stands for insertion point and

represents the location of the insertion pointer at the time—this value means that there is no text currently selected.

The contents of the current selection are expressed in characters, words, sentences, and paragraphs. There are four properties, named Characters, Words, Sentences, and Paragraphs, and they’re all collections. Use their Count property to find out the number of the corresponding items in the selection, or the Item property followed by an index value in parentheses to retrieve a specific member from the collection. The following expressions return the number of words and characters in the selected text:

WordApp.Selection.Words.Count

WordApp.Selection.Characters.Count

To access the third word in the current selection, use the following expression:

WordApp.Selection.Words.Item(3)

The various collections exposed by the Office applications are 1-based, except for the Characters collection, which is 0-based.

You can use the Selection object to enter new text into a document, as well as for formatting the text. While the Range object is a property of the Document object, the Selection object is a property of the Word.Application object and applies to the active document. To replace the current selection with new text, use the TypeText method, which accepts as argument the new text. If the selection contains any text, the old text will be replace with the new text. The selection can also be empty, in which case the new text will be inserted at the location of the insertion pointer.

The following statement inserts some text at the location of the insertion pointer, or replaces the selected text:

WordApp.Selection.TypeText(“some text”)

A good reason for using the Selection object to insert text is that you can specify the format before entering the text. To change the current character format, use the Font property of the Selection object, as shown in the following few statements:

With WordApp.Selection

.Font.Size = .Font.Size + 1

.Font.Bold = True

.TypeText(“this text stands out”)

.Font.Size = .Font.Size - 1

.Font.Bold = False

.TypeText(“back to the previous text font”) End With

When you use the Selection object to insert text into a document, you can set the character format as you go along. If you want to apply styles, however, it’s easier to use the Range object. Styles are usually applied to entire paragraphs, not isolated words or sentences. This is a good point at which to demonstrate the concepts discussed so far with an example.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

444 Chapter 10 AUTOMATING MICROSOFT OFFICE APPLICATIONS

VB.NET at Work: The WordDemo Project

With the objects and methods described so far, you have enough information to create a new document, place some text into it, format it, and then save it to a disk file. The first step is to start an instance of Word and connect to it. The WordDemo project (Figure 10.1) demonstrates how to:

Create a new document.

Insert some text and format it.

Save the new document to a user-specified DOC file.

Figure 10.1

The WordDemo project’s main form

These actions take place from within the Visual Basic application while Word is running in the background. The user doesn’t see Word’s window, not even as an icon on the taskbar. The new document is saved in a file with a name you specify through the Save File dialog box. You can open this file later with Word and edit it.

The buttons InsertAfter and TypeText create a new document and apply some formatting, using the Range and Selection objects respectively. The code behind the TypeText button uses the TypeText method of the Selection object to create a new document. Let’s start with the code of the TypeText button, detailed in Listing 10.2.

Listing 10.2: Composing a Document with the TypeText Method

Private Sub Button2_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles Button2.Click Dim doc As New Word.Document()

doc = WordApp.Documents.Add() Dim str As String

str = “Text Formatting:” With WordApp.Selection

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

PROGRAMMING WORD 445

.Font.Size = WordApp.Selection.Font.Size + 2

.Font.Bold = True

.TypeText(str)

.Font.Size = WordApp.Selection.Font.Size - 2

.Font.Bold = False

.TypeParagraph()

.Font.Color = Word.WdColor.wdColorDarkRed

.Font.Italic = False

.TypeText(“This sentence will appear in red. “)

.TypeParagraph()

.Font.Color = Word.WdColor.wdColorBlack

.Font.Italic = True

.Font.Size = WordApp.Selection.Font.Size + 2

.TypeText(“Text color was reset to black, “ & _

“but the font size was increased by two points”)

End With

Dim fName As String SaveFileDialog1.Filter = “Documents|*.doc” SaveFileDialog1.ShowDialog()

fName = SaveFileDialog1.FileName If fName <> “” Then

Try doc.SaveAs(fName)

Catch exc As Exception

MsgBox(“Failed to save document” & vbCrLf & exc.Message) End Try

End If

MsgBox(“The document contains “ & doc.Paragraphs.Count & “ paragraphs “ & _ vbCrLf & doc.Words.Count & “ words and “ & _

doc.Characters.Count & “ characters”) doc.Close(Word.wdSaveOptions.wdDoNotSaveChanges)

End Sub

This event handler makes use of the WordApp variable, which must be declared in the Form level with the following statement:

Dim WordApp As New Word.Application()

You must also add a reference to the Microsoft Word 9.0 Object library to your project.

The code changes the Font object to format the following text, and then it inserts the text with the TypeText method. The text entered is formatted according to the Font in effect. Every time you change the font attributes, they take effect for the following text. After entering the text, the code saves the document to a file. The name of the file is specified by the user on the FileSave dialog box.

You can also compose the same document using the Range object. The code behind the InsertAfter button uses the Range object to manipulate the text (insert new paragraphs and manipulate them). The following statements create a new document with a header, followed by three paragraphs, using the InsertAfter and InsertParagraphAfter methods. Listing 10.3 is the code behind the InsertAfter button.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

446 Chapter 10 AUTOMATING MICROSOFT OFFICE APPLICATIONS

Listing 10.3: Composing a Document with the Range Method

Private Sub Button1_Click(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click Dim doc As New Word.Document()

doc = WordApp.Documents.Add() With doc.Range

.InsertAfter(“A New Architecture for Building Distributed Applications”)

.InsertParagraphAfter()

.InsertAfter(“ADO.NET is the latest data access technology from “ & _ “Microsoft, geared towards distributed applications. Unlike “ & _ “its predecessor, ADO.NET uses disconnected recordsets.”)

.InsertParagraphAfter()

.InsertAfter(“The disconnected recordsets are called Datasets, and “ & _ “they may contain multiple tables. If the tables are related, “ & _ “the Dataset knows how to handle the relations and provides “ & _ “methods that allow you to move from any row of a table to the “ & _ “related rows of the other tables.”)

.InsertParagraphAfter()

.InsertParagraphAfter()

.InsertAfter(“ADO.NET uses XML to move rows between the database “ & _ “and the middle tier, as well as between the middle tier “ & _ “and the client. XML passes through firewalls, and it’s an “ & _ “ideal candidate for moving binary information between “ & _ “layers and/or different operating systems.”)

End With

Dim selRange As Word.Range

selRange = doc.Paragraphs.Item(1).Range selRange.Font.Size = 14 selRange.Font.Bold = True selRange.ParagraphFormat.Alignment = _

Word.WdParagraphAlignment.wdAlignParagraphCenter selRange = doc.Paragraphs.Item(2).Range.Sentences.Item(2) selRange.Italic = True

selRange = doc.Paragraphs.Item(3).Range.Words.Item(6) selRange.Font.Bold = True

selRange = doc.Paragraphs.Item(5).Range.Words.Item(5) selRange.Font.Bold = True

Dim fName As String SaveFileDialog1.Filter = “Documents|*.doc” SaveFileDialog1.ShowDialog()

fName = SaveFileDialog1.FileName If fName <> “” Then

Try doc.SaveAs(fName)

Catch exc As Exception

MsgBox(“Failed to save document” & vbCrLf & exc.Message) End Try

End If

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

PROGRAMMING WORD 447

MsgBox(“The document contains “ & doc.Paragraphs.Count & “ paragraphs “ & _ vbCrLf & doc.Words.Count & “ words and “ & _

doc.Characters.Count & “ characters”) doc.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

End Sub

Once the text has been added to the document, the code formats the header (the first paragraph in the document) and selected words in the document. The individual words are accessed through the Words collection of the corresponding paragraph. The following expression returns the second paragraph of the document:

doc.Paragraphs.Item(2)

If you apply the Range method to this expression, you’ll get a Range object with the text of the second paragraph:

doc.Paragraphs.Item(2).Range

Finally, you can access individual words in this paragraph with the following expression:

doc.Paragraphs.Item(2).Range.Words.Item(5)

The Edit Document button shows you how to manipulate the text in a Word document from within your VB application. The initial document (SAMPLE.DOC) contains multiple spaces between words that shouldn’t be there. To reduce multiple spaces to single space characters (a common task in editing), you can use the Find and Replace dialog box. The WordDemo application does the same by calling the Find.Execute method.

The Find method accepts a large number of arguments, and we usually specify only the arguments we’re interested in by name. If you want to simply specify the word to search for, you can specify only the FindText argument as follows:

thisDoc.Content.Find.Execute FindText:= “VB7”

where thisDoc is an object variable that represents a document.

The arguments of the Find.Execute method are the following (the order they’re listed here is the same order in which they appear in the method):

Find.Execute(FindText, MatchCase, MatchWholeWord, MatchWildChars, _

MatchSoundsLike, MatchAllWordForms, MatchForward, Wrap, _

Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, _

MatchAlefHamza, MatchControl)

The names of the arguments are self-explanatory, except for the last few, which are True/False values and determine how Word should search for the specified text in non-English languages.

Tip To find out the members of each Word enumeration, you can open the Object browser and expand Interop.Word Word (or the name of another application that’s referenced in your project). Move down to the entries beginning with WD. These are Word’s enumerations. Select an enumeration by clicking its name, and you will see the members of the enumeration in the right pane. The WDReplace enumeration, for instance, contains the following members: wdReplaceAll,

wdReplaceNone, and wdReplaceOne.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com