分享
 
 
 

Understanding the Word Object Model from a .NET Developer"s Perspective

王朝c#·作者佚名  2006-12-17
窄屏简体版  字體: |||超大  

Download the WordObject.exe from the Microsoft Download Center.

The Underpinnings: Documents and Templates

Bird's-Eye View of the Word Object Model

The Application Object

The Document Object

The Selection Object

The Range Object

The Bookmark Object

Searching and Replacing Text

Printing

Creating Word Tables

Summary

Application and Document classes. Focus on these two classes makes sense when you consider that most of the time you'll either be working with the Word application itself, or manipulating Word documents in some way.

As you dig into the Word object model, you'll find that it emulates the Word user interface, making it easy to guess that the Application object provides a wrapper around the entire application, each Document object represents a single Word document, the Paragraph object corresponds to a single paragraph, and so forth. Each of these objects has many methods and properties that allow you to manipulate and interact with it. The behaviors of the members of these objects are generally easy to guess—how about the PrintOut method? Others can be more obscure and sometimes tricky to use correctly. Once you learn the basics, you'll find that there isn't anything you can do in the Word user interface that you can't do just as easily in code. Programming in Word allows you to automate repetitive tasks, and to extend and customize the functionality built into Word.

In this document, you'll learn how to take advantage of many of the objects in Word 2003, and you will also be introduced to some of the properties, methods, and events of each object. You'll learn how to work with Word applications and documents, as well as with some of their more important methods and properties.

When you create a new Office project in Visual Studio .NET, you are given the option of creating a new Word Document or Word Template project, as shown in Figure 1.

Visual Studio .NET automatically creates a code file named ThisDocument.vb or ThisDocument.cs in your new Word project for both Document and Template projects. Open ThisDocument in your new project. You'll see that a public class named OfficeCodeBehind has already been generated for you. Expand the hidden Generated initialization code region. The OfficeCodeBehind class includes code that wraps the Word.Document and Word.Application objects:

These two variables are declared for you: ThisDocument: Represents the Word Document object, and allows access to all of the built-in Document members in Word, including methods, properties and events. ThisApplication: Represents the Word Application object, and allows access to all of the Application object's members, including events. The availability of these two predefined variables allows easy access to both Word objects in your code without having to declare separate Word.Document or Word.Application objects—just use ThisDocument and ThisApplication.

Each of the following sections digs into the Document and Application objects, picking specific members of each object for demonstration. Word has a very rich object model, and it would be impossible to dig into all of the members here: You'll get enough of the flavor of the object model to be able to get started, and you'll learn enough to use the Word online help for more details.

CType and DirectCast methods in the Visual Basic .NET code. The reason for this is that the sample project has its Option Strict setting on—this means that Visual Basic .NET requires strict type conversions. Many Word methods and properties return Object types: For example, the _Startup procedure is passed variables named application and document as Object types, and the CType function is used to explicitly convert each to Word.Application and Word.Document objects, respectively. Therefore, to be as rigorous about conversions as possible, the sample has enabled Option Strict, and handles each type conversion explicitly. If you're a C# developer reading this document, you'll likely appreciate this decision. However, as you'll see later on, there are certain Word features that don't translate well into the object-oriented paradigm—it can sometimes be more convenient to work with Option Strict off. For the most part, you'll want to work with Option Strict on; you'll learn about the few exceptions as they arise.Before you can effectively program Word, you need to understand how Word works. Most of the actions you'll perform in code have equivalents in the user interface on the menus and toolbars. There is also an underlying architecture that provides structure to those UI choices. One of the most important concepts is the idea of templates. You probably are already familiar with the concept of a template—a Word template can contain boilerplate text and styles as well as code, toolbars, keyboard shortcuts and AutoText entries. Whenever you create a new Word document, it is based on a template, which is distinguished by the .dot file name extension—Word documents have a .doc filename extension. The new document is linked to the template, and has access to all template items. If you do not specify a custom template, any new documents you create will be based on the Normal.dot default template, which is installed when you install Word.

The Normal.dot template is global in scope, and is available to every document you create. You could, if you wanted to, put all of your code in the Normal.dot and base all of the documents in your environment on your Normal template. But the file could become quite large, so for many developers, a better solution is to create customized templates for specific applications. Documents created using your custom template still have access to the code in the default Normal template. In fact, you can attach a document to more than one custom template in addition to Normal if you so desire.

You are not limited to templates as containers for styles and code; you can also customize and write code in individual documents without affecting the content of the template the document is based on. When Word runs your code, it uses the fully qualified reference of the source (which can be a template or the document), the module name, and the procedure name. This operates in a similar fashion to namespaces, keeping procedures separated. Figure 2 shows the Customize dialog box for toolbars, illustrating this concept. Each procedure is fully qualified with the name of the project, the module, and the procedure name. In this case, the item selected in the right pane refers to a procedure named TileVertical that is contained in the Tile module in Normal.dot. The SaveDocument procedure listed immediately below it is contained in the active document's code behind project.

Word allows you to format a document in two different ways: By direct formatting. You can select text and apply formatting options such as font, bold, italic, size, and so forth. By applying a style. Word comes with built-in styles that you can modify to customize your documents. When you apply a style to a paragraph or a selection, multiple attributes are applied all at once. Styles are stored in templates and in documents. Styles are normally applied to an entire paragraph: you can also define character styles that you can apply to a character, word, or range within a paragraph. You can examine the available styles by selecting Format | Styles and Formatting from the menu to bring up the Styles and Formatting pane shown in Figure 3, where the Normal paragraph style is selected.

Modify from the available options. You can modify any of the built-in styles, and optionally save your changes in the template the document is based on, as shown by the Add to template check box setting in Figure 4. If you omit this check box, your changes will be saved in the document, and will not propagate back to the template the document was based on.

When working with Word, you'll want to use styles as much as possible. Styles give you a way to control the formatting of complex documents in a way that would be very difficult to achieve with direct formatting. It's important to understand how they work so that you can take advantage of them to make your code more efficient.

When you look at a document in the Word user interface, you see the document broken up into words, paragraphs, sections, and so on. Under the covers, the Word document is nothing more than a vast stream of characters. Some of these characters are meant to be read, such as the letters and numbers, and others are not, such as spaces, tabs and carriage returns. Each of these characters has a task to perform.

In addition to separating one paragraph from another, a paragraph mark plays a very important role in a Word document: it contains all of the information about how the paragraph is formatted. When you copy a paragraph and include the paragraph mark, all of the formatting in the paragraph travels along with it. If you copy a paragraph and omit the paragraph mark, the formatting of the original paragraph will be lost when it is pasted into a new location.

When you are editing a Word document and you press the ENTER key on your keyboard, a new paragraph is created that is a clone of the previous paragraph in terms of formatting, and whatever paragraph formatting or style that was in effect is propagated in the new paragraph. You can apply different formatting to the second paragraph. On the other hand, a line break, which you create by pressing SHIFT + ENTER, simply puts in a line feed character in the existing paragraph and does not hold any formatting. If you apply paragraph formatting, it will apply to all text both before and after the line break characters.

Figure 5 shows the difference between a line break and a paragraph mark when your options are set to display paragraph marks.

If you inadvertently delete a paragraph mark, it's possible you may lose your paragraph formatting. The best course of action is to ensure that they are always displayed by choosing Tools | Options | View from the menu and selecting the Paragraph marks check box in the Formatting marks section, as shown in Figure 6.

At first glance, the Word object model is rather confusing because there appears to be a lot of overlap. For example, the Document and Selection objects are both members of the Application object, but the Document object is also a member of the Selection object. Both the Document and Selection objects contain Bookmarks and Range objects, as you can see in Figure 7. The following sections briefly describe the top-level objects and how they interact with each other.

The Application object represents the Word application, and is the parent of all of the other objects. Its members usually apply to Word as a whole. You can use its properties and methods to control the Word environment.

The Document object is central to programming Word. When you open an existing document or create a new document, you create a new Document object, which is added to the Word Documents collection. The document that has the focus is called the active document and is represented by the Application object's ActiveDocument property.

The Selection object represents the area that is currently selected. When you perform an operation in the Word user interface, such as bolding text, you select the text and then apply the formatting. The Selection object is always present in a document; if nothing is selected, the Selection object represents the insertion point. The Selection object can also be multiple noncontiguous blocks of text.

The Range object represents a contiguous area in a document, and is defined by a starting character position and an ending character position. You are not limited to a single Range object; you can define multiple Range objects in the same document. A Range object has the following characteristics: It can consist of only an insertion point, a range of text, or the entire document. It includes non-printing characters such as spaces, tab characters, and paragraph marks. It can be the area represented by the current selection, or it can represent a different area than the current selection. It is dynamic; it exists only so long as the code that creates it is running. When you insert text at the end of a range, Word automatically expands the range to include the inserted text.

The Bookmark object is similar to the Range object in that it represents a contiguous area in a document, with both a starting position and an ending position. You use bookmarks to mark a location in a document, or as a container for text in a document. A Bookmark object can consist of the insertion point alone or be as large as the entire document. You can also define multiple bookmarks in a document. A Bookmark has the following characteristics, setting it apart from the Range object: You can give the Bookmark object a name. It is saved with the document, and does not go away when the code stops running or your document is closed. It is hidden by default, but can be made visible by setting the View object's ShowBookmarks property to True. (The View object is a member of the Window and Pane objects, which exist for both the Application and Document objects.) Here are some scenarios for using the Selection, Range, and Bookmark objects: Bookmarks are useful in templates. For example, a business letter template can contain bookmarks where data is to be inserted from a database. At run time, your code can create a new document based on the template, obtain the data from a database, locate the named bookmark, and insert the text in the correct location. If you need to modify the text inside of a Bookmark, you can use the Bookmark's Range property to create a Range object, and then use one of the Range object's methods to modify the text. You can define boilerplate text in a document by using a Bookmark object. You specify its contents using a Range or a Selection object as the source. You can then conditionally navigate to various Bookmarks at some future time to copy and paste the boilerplate text into other documents. These are just a few of the ways in which you can make use of these objects to build powerful customized applications.

The Word Application object represents the Word application itself. Every time you write code, you begin with the Application object. From the Application object, you can access all the other objects and collections exposed by Word, as well as properties and methods of the Application object itself.

If you are working in Word, the Application object is automatically created for you, and you can use the Application property to return a reference to the Word Application object. When you're creating Visual Studio .NET solutions, you can use the ThisApplication variable defined for you within the OfficeCodeBehind class.

If you are automating Word from outside this class, you must create a Word Application object variable and then create an instance of Word:

Word.Application variable works in your OfficeCodeBehind class the same way that ThisApplication does. However, it's an unnecessary extra step to explicitly create a new Word.Application variable because ThisApplication has already been created for you.When you're referring to objects and collections beneath the Application object, you don't need to explicitly refer to the Application object. For example, you can refer to the active document without the Application object by using the built-in ThisDocument property. ThisDocument refers to the active document, and allows you to work with members of the Document object. The Document object will be covered more fully in later sections of this document.

ThisApplication.ActiveDocument property, which refers to the active Document object, is likely the one you'll use most often. You'll generally want to use ThisDocument instead of ThisApplication.ActiveDocument syntax. ActiveDocument is available, but you need to fully qualify it with an Application object in order to use it in your code. Using ThisDocument is more efficient as the variable is already created for you, and amounts to the same thing.Once you have a reference to an Application object, you can work with its methods and properties. The Application object provides a large set of methods and properties that you can use in your code to control Word. Most of the members of the Application object apply to global settings or the environment rather than to the contents of individual documents. Setting or retrieving some properties often requires only a single line of code; other retrievals are more complex. ActiveWindow: Returns a Window object that represents the window that has the focus. This property allows you to work with whatever window has the focus. The sample code below creates a new window based on the current document and then uses the Arrange method of a Window object to tile the two windows. Note that the Arrange method uses the WdArrangeStyle.wdTiled enumerated value.

Arrange method, like many methods in Word, requires C# developers to pass one or more parameters using the "ref" keyword. This means that the parameter you pass must be stored in a variable before you can pass it to the method. In every case, you'll need to create an Object variable, assign the variable the value you'd like to pass to the method, and pass the variable using the ref keyword. You'll find many examples of this technique throughout this document.ActiveDocument: Returns a Document object that represents the active document or the document that has the focus ActivePrinter: Returns or sets the name of the active printer ActiveWindow: Returns the window that has the focus AutoCorrect: Returns the current AutoCorrect options, entries, and exceptions. This property is read-only. Caption: Returns or sets the caption text for the specified document or application window. You can use the Caption property to display "My New Caption" in the document window or application title bar:

CapsLock: Determines whether CapsLock is turned on, returning a Boolean value. The following procedure displays the state of CapsLock:

DisplayAlerts: Lets you specify how alerts are handled when code is running, using the WdAlertLevel enumeration. WdAlertlevel contains three values: wdAlertsAll, which displays all messages and alerts (the default); wdAlertsMessageBox, which displays only message boxes; and wdAlertsNone, which does not display any alerts or message boxes. When you set DisplayAlerts to wdAlertsNone, your code can execute without the user seeing any messages and alerts. When you're done, you'll want to ensure that DisplayAlerts gets set back to wdAlertsAll (generally, you'll reset this in a Finally block):

DisplayStatusBar: Read/write, returns a Boolean indicating whether or not the status bar is displayed. Returns True if it is displayed and False if it is not. The following procedure toggles the display of the status bar:

FileSearch: Searches for files using either an absolute or a relative path. You supply the search criteria, and FileSearch returns the name of the files found in the FoundFiles collection.

Execute method, as they're all optional. C# developers, however, must pass every parameter. In this case, the code supplies values that match the default values. For reference-type parameters, you can pass the Type.Missing value, indicating to Word that it should treat the parameters as if you hadn't passed a value at all. For value-type parameters, you must specify an actual value. You can use the Word VBA help file to determine the default values for the value-type parameters.Path: When used with the Application object, returns the path of the current application:

Options: Returns an Options object that represents application settings for Word, allowing you to set a variety of options in your application. Many, but not all, of these options are available in the Tools | Options dialog box. The following code fragment will turn on the BackgroundSave and Overtype properties, among others. If the file is printed, any fields will be automatically updated, and hidden text and field codes will be printed.

Selection: A read-only object that represents a selected range (or the insertion point). The Selection object is covered in detail later in this document. UserName: Gets or sets the user name. The following procedure displays the current user's name, sets the UserName property to "Dudley" and displays the new UserName. The code then restores the original UserName.

Visible: A read/write property that turns the display of the Word application itself on or off. While the Visible property is False, all open Word windows will be hidden, and it will appear to the user that Word has quit and all document are closed (they are still running in the background). Therefore, if you set the Visible property to False in your code, make sure to set it to True before your procedure ends. The following code accomplishes this in the Finally block of a Try/Catch exception handler:

There are several methods of the Application object that you may find useful for performing actions involving the Word application. Writing code to make use of Application object methods is similar to working with properties. Use the following methods to perform actions on the application itself: CheckSpelling: Checks a string for spelling errors. Returns True if errors are found, and False if no errors. This is handy if you just want to spell check some text to obtain a yes/no answer to the question "Are there any spelling errors?"—It doesn't display the errors or allow you to correct them. The following code checks the string "Speling erors here" and displays False in a MessageBox.

CheckSpelling method accepts a single required string parameter, followed a large number of optional parameters. C# developers must pass a series of values by reference—in this case, a group of variables all containing the Type.Missing value. You'll find it useful, if you must call methods like CheckSpelling multiple times, to create a "helper" class that wraps up the method call. This class could include methods that expose only the most useful parameters for the Word method calls.Help: Displays Help dialog boxes. Specify a member of the WdHelpType enumeration to choose the particular dialog box, selecting from the following list: WdHelp: Displays the Microsoft Word main Help dialog box WdHelpAbout: Displays the dialog box available from the Help | About Microsoft Word menu item WdHelpSearch: Displays the main Help dialog box with the Answer Wizard displayed The following line of code will display the Help About Microsoft Word dialog box:

Move: Moves the application's main window based on the required Left and Top arguments, which are both Integer values Resize: Resizes the application's main window based on the required arguments Width and Height (in points). This example moves the application to the uppermost left corner of the screen and sizes it too:

Quit: Quits Word. You can optionally save any open documents, passing a value from the WdSaveOptions enumeration: wdSaveChanges, wdPromptToSaveChanges, and wdDoNotSaveChanges. The following fragment shows all three different ways to quit Word:

Application.Quit method adds to the list of methods that require special handing in C#. In this case, the method requires three parameters, each passed by reference.SendFax: Launches the Fax Wizard, as shown in Figure 8. The user can then step through the Wizard to complete the operation.

When working with Word, there are times when you need to display dialog boxes for user input. Although you can create your own, you might also want to take the approach of using the built-in dialog boxes in Word, which are exposed in the Application object's Dialogs collection. This allows you to access over 200 of the built-in dialog boxes in Word, represented as values in the WdWordDialog enumeration. To use a Dialog object in your code, declare it as a Word.Dialog:

To specify the Word dialog you're interested in, assign the variable to one of the values returned from the array of available dialogs:

Once you've created the Dialog variable, you can make use of its methods. The Show method displays the dialog box as though the user had selected it manually from the Word menus. The following procedure displays the File New dialog box:

Show method allows you to specify a TimeOut parameter, indicating the number of milliseconds to wait before automatically closing the dialog box. In Visual Basic .NET, you can ignore the parameter. In C#, pass Type.Missing by reference to indicate the default value—no timeout at all.Another good use for the Word dialogs is to spell check a document. The following procedure launches the spell checker for the active document with the wdDialogToolsSpellingAndGrammar enumeration:

In addition to the Show method, there are three additional methods that you can use with Word dialog boxes: Display, Update, and Execute: Display: Displays the specified built-in Word dialog box until either the user closes it or the specified amount of time has passed. It does not execute any of the actions that the dialog box normally would. You can also specify an optional timeout value. The code in the following procedure uses the Display method, supplying an optional Timeout value that will display the UserInfo dialog box for approximately three seconds. If the user does not dismiss the dialog, it will automatically close:

Object variable, place the literal value into the variable, and pass the variable by reference. If you care about which button the user chooses in dismissing a dialog box, you can return the result of the Display method in an Integer variable so that you can branch in your code depending on the button selected. For example, a user might have edited the name of the user in the UserInfo dialog box. If the user clicks the OK button, they expect their changes to be saved, and if they click the Cancel button, they expect any edits to be abandoned.

The possible return values are displayed in Table 1:

ValueButton Clicked-2

The Close button

-1

The OK button

0 (zero)

The Cancel button

> 0 (zero)

A command button: 1 is the first button, 2 is the second button, and so on.

Unless you take explicit action to save changes made in this dialog box, it doesn't matter which button the user selects; all changes will be thrown away. You need to use the Execute method to explicitly apply changes within the dialog box. Execute: If you simply call the Display method and the user changes values in the dialog box, those changes won't be applied. You need to use the Execute method after the Display method to explicitly apply any changes the user made. Unlike the Save method that saves user changes, all changes will be discarded even if the user clicks OK. The following code calls the UserInfo dialog box using Display, and then the code checks the return value of the Integer variable. If the user clicked the OK button (returning a value of -1), the code uses the Execute method to apply the changes:

ThisApplication.UserName property.Update: Use the Update method when you want to ensure that the dialog box is displaying the correct values. Because you can modify the contents of the dialog box using code, even after you've retrieved a reference to the dialog box, you may need to update the contents of the dialog box before displaying it. (See the next section for information on using the Word dialog boxes in hidden mode—that's when you would need this method.) Because of the way the Word dialog boxes have been designed, all the properties of the various dialogs that correspond to values of controls on the forms are available only at run time. That is, when Word loads the dialog box, it creates the various properties and adds them at run time to the appropriate objects. This type of scenario makes it difficult for developers working in a strongly typed world (as in C#, and in Visual Basic .NET with Option Strict set to On) to write code that compiles.

For example, the Page Setup dialog box (represented by the WdWordDialog.wdDialogFilePageSetup enumeration) provides a number of properties dealing with page setup, including PageWidth, PageHeight, and so on. You'd like to be able to write code like the following to access these properties:

Unfortunately, this code simply won't compile in Visual Basic .NET with Option Strict set On, or in C# at all—the PageWidth and PageHeight properties aren't defined for the Dialog object until run time.

You have two options for working with these properties: you can either create a Visual Basic file that includes the Option Strict Off setting at the top, or you can find a way to perform late binding. (You could, of course, work through the intricacies of using the System.Reflection namespace to perform the late binding yourself—that's what Visual Basic .NET does when you turn Option Strict off, under the covers.) The CallByName method, provided by the Microsoft.VisualBasic assembly, allows you to specify the name of the property with which you want to interact, as a string, along with the value for the property and the action you'd like to take. You can use this method whether you're a Visual Basic .NET or a C# developer. C# developers will, of course, need to add a reference to the Microsoft.VisualBasic assembly in order to take advantage of this technique.

Once you've referenced the assembly, you can add code like the following:

It's not a perfect solution—the code is tricky to read and write, and requires C# developers to use methods from Visual Basic (which may seem too draconian a solution, in any case), but it does provide a simple way to work with an otherwise unavailable set of properties.

The sample project includes the following procedure, which modifies the page settings for the current document, using the Page Setup dialog box. Note that this code uses the Execute method of the Dialog class, and never actually displays the dialog box—this is perfectly valid behavior, and this technique provides a simple way to set a large number of properties in one place without requiring you to dig around into multiple objects:

ConvertToInches method, which handles tacking on the necessary quote mark. The odd thing is that the PageWidth and PageHeight properties use the default units set by the user, whereas the other properties in this example require either points or a string containing a value with the unit indicator. The call to ConvertToInches is therefore unnecessary, in countries that use inches by default, for the first two properties in the example. Calling the method can't hurt, however.When deciding whether or not to use the built-in dialog boxes, consider the amount of work that you are doing. If you are only setting a couple of properties in a single object, you're probably better off simply working with that object. If you need to display an interface for your users to interact with, your best bet is to use the corresponding dialog box. Consult the Word Help file for information on using the other Word built-in dialog boxes.

Dialog object, you'll need to look deeper than the included Word help file. This file barely touches on the huge set of dialog boxes provided by Word. To find more information, you'll need the WordBasic help file, from Word 95. You can find this help file on www.microsoft.com. Search for "Word 95 WordBasic Help File" to locate the correct page.The bulk of your programming activity in Word will involve the Document object or its contents. When you work with a particular document in Word, it is known as the active document, and can be referenced by the Application object's ActiveDocument property. All Word Document objects are also members of the Application object's Documents collection, which consists of all open documents. Using the Document object allows you to work with a single document, and the Documents collection allows you to work with all open documents. The Application and Document classes share many members as it is possible to perform document operations at both the Application and Document levels.

Some common tasks you can perform involving documents include: Creating and opening documents Adding, searching and replacing text Printing A document consists of characters arranged into words, with words structured into sentences. Sentences are arranged into paragraphs, which can, in turn, be arranged inside of sections. Each section contains its own headers and footers. The Document object has collections that map to these constructs: Characters Words Sentences Paragraphs Sections Headers/Footers You can refer to a Document object as a member of the Documents collection by using its index value. The index value is the Document object's location in the Documents collection, which is a 1-based collection (like all the collections within Word). The following code fragment sets an object variable to refer to the first Document object in the Documents collection:

You can also reference a document by its name, which is usually a better choice if you want to work with a specific document. You will rarely refer to a document by using its index value in the Documents collection because this value can change for a given document as other documents are opened and closed. The following code fragment sets an object variable to point to the named document, "MyDoc.doc":

If you want to refer to the active document (the document that has the focus), you can use the ActiveDocument property of the Application object. You already have the property created for you in the Visual Studio .NET project, so your code will be more efficient if you use the ThisDocument reference when you need to refer to the document that has the focus. The following code fragment retrieves the name of the active document:

The reference to the ThisDocument object in your Word project gives you access to all members of the Document object, allowing you to work with its methods and properties, as applied to the active document. The first step in working with the Document object is to open an existing Word document or to create a new one.

When you create a new Word document, you add it to the Application's Documents collection of open Word documents. Consequently, the Add method creates a new Word document. This is the same as clicking on the New Blank Document button on the toolbar.

Documents.Add method accepts up to four optional parameters, indicating the template name, a new template name, the document type, and the visibility of the new document. In C#, you must pass Type.Missing by reference for each of these optional parameters in order to take advantage of the default value for each parameter.The Add method has an optional Template argument to create a new document based on a template other than Normal.dot. You need to supply the fully qualified path and file name where the template can be found.

This code achieves the same result as a user choosing File | New from the menu and choosing a template from the New Document toolbar. When you write code specifying the Template argument, you can ensure that all documents will be created using the specified template. Coding your own new file routine might be easier in the long run for your users, who might be confused when it comes to choosing the correct template.

The Open method opens an existing document. The basic syntax is very simple—you use the Open method and supply the fully qualified path and file name. There are other optional arguments that you can supply, such as a password or whether to open the document read-only, which you can find by using IntelliSense in the code window. The following code opens a document, passing only one of several optional parameters. The C# code, of course, must pass all the parameters, only supplying a real value for the FileName parameter:

There are several ways to save and close documents, depending on what you want the end result to be. The two methods you use to save and close documents are Save and Close, respectively. They have different results depending on how they are used. If applied to a Document object, only that document is affected. If applied to the Documents collection, all open documents are affected. Save all Documents: The Save method saves changes to all open documents when applied to the Documents object. There are two different ways to use it, depending on whether you want the user to be prompted to save changes or whether you want the save operation to proceed without user intervention. If you simply call the Save method on the Documents collection, the user will be prompted to save all files.

The following code sets the NoPrompt parameter to True, and saves all open documents without user intervention.

NoPrompt is False, so if you call Save without specifying a NoPrompt value in Visual Basic .NET, or by specifying Type.Missing in C#, the user will be prompted to save.Save a Single Document: The Save method saves changes to a specified Document object. The following code fragment shows two ways to save the active document:

If you're not sure if the document you want to save is the active document, you can refer to it by its name. This code uses the Save method on a named document.

Item property, or leaving out this optional call, and supplying an index or name), C# developers generally cannot. Instead, C# developers generally must call the hidden get_Item method, passing an index or name by reference, as in the previous example. C# developers can directly access elements of arrays (as in the Dialogs array, shown previously), but for collections, you'll need to use the get_Item method.An alternate syntax would be to use the document's index number, although that isn't as reliable for two reasons. The first is that you can't be sure which document is being referred to since the index number can change, and the second is that if the referenced document hasn't been saved yet the save dialog box will appear. The following code saves the first document in the Documents collection:

SaveAs: The SaveAs method allows you to save a document under another file name. It requires that you specify the new file name, but other arguments are optional. The following procedure saves a document with a hard coded path and file name. If a file by that name already exists in that folder, it will be silently overwritten. (Note that the SaveAs method accepts several optional parameters, all of which must be satisfied in C#.)

The Close method can be used to save documents as well as close them. You can close documents individually or close all at once. Closing All Documents: The Close method works similarly to the Save method when applied to the Documents collection. When called with no arguments, it prompts the user to save changes to any unsaved documents.

Like the Save method, the Close method accepts an optional SaveChanges argument that has three WdSaveOptions enumerations you can use: wdDoNotSaveChanges, wdPromptToSaveChanges, or wdSaveChanges. The following lines of code close all open documents, silently saving and discarding changes respectively:

Application.Quit method, Word shuts down. Closing all open documents doesn't cause Word to quit—if you close all open documents, Word will still be running and you'll still need to shut it down.Close a Single Document: The code fragments listed here close the active document without saving changes, and close MyNewDocument silently saving changes:

Most of the time you probably aren't going to be interested in iterating through the entire Documents collection: you'll want to work with an individual document. There are occasions when you want to visit each open document and conditionally perform some operation. You can refer to a Word document in the Documents collection by its name, by its index in the collection, or you can use a For Each (in Visual Basic .NET) or foreach (in C#) loop to iterate through the documents. Inside the loop, you can conditionally perform operations on selected files. In this example, the code walks through all open documents, and if a document hasn't been saved, saves it.

The code in the sample procedure takes the following actions: Loops through the collection of open documents Checks the Saved property of each document and saves the document if it hasn't been saved Collects the name of each saved document Displays the name of each saved document in a MessageBox, or a message indicating that no documents need saving based on the length of the string

The Selection object represents the area in a Word document that is currently selected. When you perform an operation in the Word user interface, such as bolding text, you select the text and then apply the formatting. You use the Selection object the same way in your code: define the Selection and then perform the operation. You can use the Selection object to select, format, manipulate, and print text in your document.

The Selection object is always present in a document. If nothing is selected, it represents the insertion point. Therefore, it's important to know what a Selection object consists of before you attempt to do anything with it.

Selection and Range objects have many members in common. The difference is that a Selection object refers to what is displayed in the user interface, whereas a Range object is not displayed (although it can be, by calling its Select method).Selection object. If you need to work with a portion of the document but don't want to modify the user's selection, use a specific range, paragraph, sentence, and so on.There are various types of selections and it's important to know what, if anything, is selected. For example, if you're performing an operation on a column in a table, you'd like to ensure that the column is selected to avoid triggering a run-time error. This is easily achieved with the Type property of the Selection object. The Type property contains the following WdSelectionType enumerated values that you can use in your code to determine what is selected: wdSelectionBlock wdSelectionColumn wdSelectionFrame wdSelectionInlineShape wdSelectionIP wdSelectionNormal wdNoSelection wdSelectionRow wdSelectionShape The intended purpose of most of the enumerations are obvious given their names, but some are a little more obscure. For example, wdSelectionIP represents the insertion point. The wdInlineShape value represents an image or a picture. The value wdSelectionNormal represents selected text, or a combination of text and other selected objects.

The code in the following procedure works with the Selection's Type property in order to determine the type of selection. To test it, enter and select some text within the sample document, then run the demo form. The code doesn't do much after determining the current Selection object's Type property. It simply uses a Case structure to store the value in a string variable to display in a MessageBox:

In addition to determining what has been selected, you can also use the following methods of the Selection object to navigate and select different ranges of text in a document. These methods mimic the actions of keys on your keyboard.

Using these methods also changes the selection.

HomeKey([Unit], [Extend]): Acts is if you'd pressed the HOME key on your keyboard.

EndKey([Unit], [Extend]): Acts as if you'd pressed the END key on the keyboard.

You use one of the following wdUnits enumerations for the Unit argument, which determines the range of the move: WdLine : Move to the beginning or the end of a line. This is the default value. WdStory: Move to the beginning or the end of the document. WdColumn: Move to the beginning or end of a column. Valid for tables only. WdRow: Move to the beginning or the end of a row. Valid for tables only. You use one of the following WdMovementType enumerations for the Extend argument, which determines whether the Selection object will be an extended range or the insertion point: WdMove: Moves the selection. The end result is that the new Selection object consists of the insertion point. When used with wdLine, it moves the insertion point to the beginning or end of the line. When used with wdStory, it moves the insertion point to the beginning or end of the document. WdExtend: Extends the selection. The end result is that the new Selection object consists of a range that extends from the insertion point to the end point. If the starting point is not the insertion point, the behavior varies depending on the method used. For example, if a line is currently selected and the HomeKey method is called with the wdStory and wdExtend enumerations, the line will not be included in the new selection. If the EndKey method is called with the wdStory and wdExtend enumerations, the line will be included in the selection. This behavior mirrors the keyboard shortcuts CTRL+SHIFT+HOME and CTRL+SHIFT+END, respectively. The following code moves the insertion point to the beginning of the document using the HomeKey method with the wdStory and the WdMovementType wdMove enumerations. The code then extends the selection to the end of the document using the EndKey with the wdExtend enumeration:

' Position the insertion point at the beginning of the document.ThisApplication.Selection.HomeKey( _ Word.WdUnits.wdStory, Word.WdMovementType.wdMove)' Select from the insertion point to the end of the document.ThisApplication.Selection.EndKey( _ Word.WdUnits.wdStory, Word.WdMovementType.wdExtend)// C#// Position the insertion point at the beginning // of the document.Object unit = Word.WdUnits.wdStory;Object extend = Word.WdMovementType.wdMove;ThisApplication.Selection.HomeKey(ref unit, ref extend);// Select from the insertion point to the end of the document.unit = Word.WdUnits.wdStory;extend = Word.WdMovementType.wdExtend;ThisApplication.Selection.EndKey(ref unit, ref extend);

You can also move a selection with the following methods, each of which have a Count argument that determines the number of units to move for a given direction. These methods correspond to using the cursor arrow keys on your keyboard: MoveLeft([Unit], [Count], [Extend]) MoveRight([Unit], [Count], [Extend]) MoveUp([Unit], [Count], [Extend]) MoveDown([Unit], [Count], [Extend]) The Extend argument takes the same two enumerations, wdMove and wdExtend. You have a different selection of WdUnits enumerations for the Unit argument for MoveLeft and MoveRight: wdCharacter: Move in character increments. This is the default value. wdWord: Move in word increments. wdCell: Move in cell increments. Valid for tables only. wdSentence: Move in sentence increments. The following code fragment moves the insertion point to the left three characters, and then selects the three words to the right of the insertion point.

// C#// Move the insertion point left 3 characters.Object unit = Word.WdUnits.wdCharacter;Object count = 3;Object extend = Word.WdMovementType.wdMove;ThisApplication.Selection.MoveLeft(ref unit, ref count, ref extend);// Select the 3 words to the right of the insertion point.unit = Word.WdUnits.wdWord;count = 3;extend = Word.WdMovementType.wdExtend;ThisApplication.Selection.MoveRight(ref unit, ref count, ref extend);

The MoveUp and MoveDown methods take the following enumerations for WdUnits: wdLine: Moves in line increments. This is the default value. wdParagraph: Moves in paragraph increments wdWindow: Moves in window increments wdScreen: Moves in screen increments The following code fragment moves the insertion point up one line, and then selects the three following paragraphs. What actually ends up being selected depends on where the insertion point is or whether a range of text is selected at the beginning of the operation.

The Move method collapses the specified range or selection and then moves the collapsed object by the specified number of units. The following code fragment collapses the original Selection object and moves three words over. The end result is an insertion point at the beginning of the third word, not the third word itself:

The simplest way to insert text in your document is to use the TypeText method of the Selection object. TypeText behaves differently depending on the user's options. The code in the following procedure declares a Selection object variable and turns off the overtype option if it is turned on. If the overtype option is activated, any text next to the insertion point will be overwritten:

The code then tests to see if the current selection is an insertion point. If it is, the code inserts a sentence using TypeText, and then a paragraph mark by using the TypeParagraph method:

The code in the ElseIf/else if block tests to see if the selection is a normal selection. If it is, another If block tests to see if the ReplaceSelection option is turned on. If it is, the code uses the Selection's Collapse method to collapse the selection to an insertion point at the start of the selected block of text. The text and a paragraph mark are then inserted:

If the selection is not an insertion point or a block of selected text, the code simply does nothing at all.

You can also use the TypeBackspace method of the Selection object, which mimics the functionality of the BACKSPACE key on your keyboard. But when it comes to inserting and manipulating text, the Range object offers you more control.

The Range object represents a contiguous area in a document, and you create one by defining by a starting character position and an ending character position. You are not limited to a single Range object; you can define multiple Range objects in the same document. If you define both the start and end of the range at the same location, the result will be a range that consists of an insertion point. Or you can define a range that encompasses the entire document by starting at the first character and including the last character. Note that the range also includes all non-printing characters, such as spaces, tabs, and paragraph marks.

The Range object shares many members with the Selection object. The main difference between the two is that the Selection object always returns a reference to the selection in the user interface, and the Range object allows you to work with text without displaying the range in the user interface.

The main advantages of using a Range object over a Selection object are: The Range object generally requires fewer lines of code to accomplish a given task. The Range object doesn't incur the overhead associated with Word having to move or change the highlighting in the active document. The Range object has greater capabilities than the Selection object, as you'll see in the following section. You can define a range in a document by using the Range method of a Document object to supply a start value and an end value. The following code creates a new Range object that includes the first seven characters in the active document, including non-printing characters. It then uses the Range object's Select method to highlight the range. If you omit this line of code, the Range object will not be selected in the Word user interface, but you'll still be able to manipulate it programmatically.

Figure 9 shows the results, which include the paragraph mark and a space.

The first character in a document is at character position 0, which represents the insertion point. The last character position is equal to the total number of characters in the document. You can determine the number of characters in a document by using the Characters collection's Count property. The following code selects the entire document and displays the number of characters in a MessageBox:

Range method without any parameters returns the entire range—you needn't specify the start and end values if you simply want to work with the entire contents of the document. This doesn't hold true for C# developers, of course, because you must always pass values for all the optional parameters. In C#, you can pass Type.Missing for all optional parameters to assume the default values.If you don't care about the number of characters and all you want to do is to select the entire document, you can use the Document object's Select method on its Range property:

If you want to, you can use the Document object's Content property to define a range that encompasses the document's main story—that is, the content of the document not including headers, footers, and so on:

You can also use the methods and properties of other objects to determine a range. The code in the next procedure takes the following actions to select the second sentence in the active document: Creates a Range variable Checks to see if there are at least two sentences in the document Sets the Start argument of the Range method to the start of the second sentence Sets the End argument of the Range method to the end of the second sentence Selects the range

Range property are declared as System.Object, so the code must convert these values explicitly. If you're working in Visual Basic .NET with Option Strict set to Off, this won't be necessary. If you're working in C#, you must pass these values by reference, as you've already seen.Documents collection, which requires C# developers to use the hidden get_Item method to retrieve individual elements, the Paragraphs, Sentences, and other properties return arrays. Therefore, C# developers can index into these arrays just as they would any other array.If all you want to do is to select the second sentence, you can do so in fewer lines of code by setting the range directly to the Sentence object. The following code fragment is equivalent to the previous procedure listing:

Once you define a Range object, you can extend its current range by using its MoveStart and MoveEnd methods. The MoveStart and MoveEnd methods each take the same two arguments: Unit and Count. The Unit argument can be one of the following WdUnits enumerations: wdCharacter wdWord wdSentence wdParagraph wdSection wdStory wdCell wdColumn wdRow wdTable The Count argument specifies the number of the units to move. The following code defines a range consisting of the first seven characters in the document. The code then uses the Range object's MoveStart method to move the starting point of the range by seven characters. Because the end of the range is also seven characters, the result is a range consisting of the insertion point. The code then moves the ending position by seven characters using the MoveEnd method.

Figure 10 shows how the code progresses; the top line is the initial range, the second line is after the MoveStart method has moved the starting position by seven characters (the range is an insertion point, displayed as an I-bar), and the third line displays the characters selected after the MoveEnd statement moves the end of the range by seven characters.

You can retrieve the character positions of the start and end positions of a range by retrieving the Range object's Start and End properties, as shown in the following code fragment:

You can also use SetRange to resize an existing range. The following code sets an initial Range starting with the first seven characters in the document. Next, it uses SetRange to start the range at the second sentence and end it at the end of the fifth sentence:

You can also use the Range object to format text. The steps you need to take in your code are: Define the range to format. Apply the formatting. Optionally select the formatted range to display it. The code in the sample procedure selects the first paragraph in the document and changes the font size, font name, and the alignment. It then selects the range and displays a MessageBox to pause before executing the next section of code, which calls the Document object's Undo method three times. The next code block applies the Normal Indent style and displays a MessageBox to pause the code. Then the code calls the Undo method once, and displays a MessageBox.

Range.Style property expects a Variant, C# developers must call the hidden set_Style method of the Range class in order to set the style. Pass either the name of the style or a Style object by reference to the set_Style method in order to apply a style to the range. In cases in which a read/write property has been defined as a Variant in VBA, C# developers must call the appropriate hidden accessor methods, like set_Style and get_Style. Visual Basic .NET developers can simply set or get the value of the property directly.You can use the Text property of a Range object to insert or replace text in a document. The following code fragment specifies a range that is the insertion point at the beginning of a document and inserts the text " New Text " (note the spaces) at the insertion point. The code then selects the Range, which now includes the inserted text. Figure 11 shows the results after the code has run.

If your range is a selection and not the insertion point, all text in the range is replaced with the inserted text. The following code creates a Range object that consists of the first 12 characters in the document. The code then replaces those characters with the string.

If you are working with a Range or Selection object, you may want to change the selection to a prior insertion point to avoid overwriting existing text. Both the Range and Selection objects have a Collapse method that makes use of two WdCollapseDirection enumerated values: WdCollapseStart: Collapses the selection to the beginning of the selection. This is the default if you do not specify an enumeration. WdCollapseEnd: Collapses the selection to the beginning of the selection. The following procedure creates a Range object consisting of the first paragraph in the document. It then uses the wdCollapseStart enumeration to collapse the range. Next, it inserts the new text and selects the range. Figure 13 shows the results.

If you use the wdCollapseEnd value, the new text gets inserted at the beginning of the following paragraph:

You might have expected that inserting the new sentence would have inserted it before the paragraph marker, but that is not the case as the original range includes the paragraph marker. The next section addresses how to work with paragraph marks to insert text safely.

Whenever you create a Range object based on a paragraph, all non-printing characters are included as well. The following example procedure declares two string variables and retrieves the contents of the first and second paragraphs in the active document:

The following code creates two Range variables for the first and second paragraphs and assigns the Text property, swapping the text between the two paragraphs. The code then selects each range in turn, pausing with MessageBox statements in between so that the results are displayed. Figure 15 shows the document after the swap, with rng1 selected.

' Swap the paragraphs. Dim rng1 As Word.Range = _ ThisDocument.Paragraphs(1).Range rng1.Text = str2 Dim rng2 As Word.Range = _ ThisDocument.Paragraphs(2).Range rng2.Text = str1 ' Pause to display the results. rng1.Select() MessageBox.Show(rng1.Text, "ManipulateRangeText") rng2.Select() MessageBox.Show(rng2.Text, "ManipulateRangeText")// C# // Swap the paragraphs. Word.Range rng1 = ThisDocument.Paragraphs[1].Range; rng1.Text = str2; Word.Range rng2 = ThisDocument.Paragraphs[2].Range; rng2.Text = str1; // Pause to display the results. rng1.Select(); MessageBox.Show(rng1.Text, "ManipulateRangeText"); rng2.Select(); MessageBox.Show(rng2.Text, "ManipulateRangeText");

The next section of code adjusts rng1 using the MoveEnd method so that the paragraph marker is no longer a part of rng1. The code then replaces the rest of the text in the first paragraph, assigning the Range's Text property to a new string:

The following section of code simply replaces the text in rng2, including the paragraph mark:

The code then selects rng1 and pauses to display the results in a MessageBox, and then does the same with rng2. Because rng1 was redefined to exclude the paragraph mark, the original formatting of the paragraph is preserved. A sentence was inserted over the paragraph mark in rng2, which obliterated it as a paragraph. Figure 16 shows rng2 highlighted; it has been merged into what was formerly the third paragraph and no longer exists as a paragraph on its own.

Because the original contents of both ranges were saved as String variables, it's not too hard to restore the document to its original condition with the two paragraphs in their original order. The next line of code readjusts rng1 to include the paragraph mark by using the MoveEnd method to move the mark by one character position:

The code then deletes rng2 entirely. This will restore the third paragraph to its original position.

The code then restores the original paragraph text in rng1:

The last section of code uses the Range object's InsertAfter method to insert the original second paragraph's content after rng1, and then selects rng1.

Figure 17 displays the three paragraphs, with rng1 selected. Note that the second paragraph is now included in rng1, which has been extended to include the inserted text.

}

The Bookmark object is similar to the Range and Selection objects in that it represents a contiguous area in a document, with both a starting position and an ending position. You use bookmarks to mark a location in a document, or as a container for text in a document. A Bookmark object can consist of the insertion point, or be as large as the entire document. You can also define multiple bookmarks in a document. You can think of a Bookmark as a named location in the document that is saved with the document.

The Bookmarks collection exists as a member of the Document, Range, and Selection objects. The following sample procedure shows how to create bookmarks in a document and use them for inserting text. The code takes the following actions: Declares a Range and two Bookmark variables and sets the ShowBookmarks property to True. Setting this property causes a Bookmark set as an insertion point to appear as a gray I-bar, and a Bookmark set to a range of text to appear as gray brackets surrounding the bookmarked text.

Defines a Range object as the first insertion point at the beginning of the document

Adds a Bookmark named bookMk1consisting of the Range object and displays a MessageBox to halt the execution of the code. At this point, you'll see the Bookmark displayed as a faint I-bar to the left of the start of the paragraph, as shown in Figure 18.

Uses the Range method's InsertBefore method to insert text before the Bookmark and pauses the code with a MessageBox. Figure 19 displays the Bookmark and the inserted text. Note that the text is inserted after the Bookmark, and in fact is now included in the bookmark.

Uses the Range method's InsertAfter method to insert text after the Bookmark. Note that the inserted text appears directly after the text that was inserted before the Bookmark, as shown in Figure 20.

Resets the Range object to point to the second paragraph in the document and creates a new Bookmark object named bookMk2 on the second paragraph. When the code pauses to display the MessageBox, you can see the Bookmark brackets surrounding the second paragraph, as shown in Figure 21.

Uses InsertBefore to insert text before the Bookmark. Figure 22 shows that the inserted text is now included in the Bookmark.

Uses InsertAfter to insert text after the Bookmark. Note that this text is inserted outside of the Bookmark, and is not included in the Bookmark. Figure 23 shows the document after the Bookmark's Select method has run.

The Bookmarks collection contains all of the bookmarks in a document. In addition, bookmarks can exist in other sections of the document, such as headers and footers. You can visit each Bookmark object and retrieve its properties. The following procedure iterates through the Bookmarks collection and displays the name of each Bookmark in the document and its Range.Text property using the MessageBox.Show method:

Updating a bookmark's text is easy—you simply assign a value to the Range.Text property of the bookmark. Doing so, however, deletes the entire bookmark. There is no easy way to insert text into a placeholder bookmark so that you can retrieve the text at a later time. One option is to replace the bookmark with the inserted text and delete the bookmark. You then re-create the bookmark around the inserted text. The following procedure demonstrates this technique, with results shown in Figure 24.

}

An easier way to update the contents of a Bookmark is to reset its Range property after modifying its text. The following procedure has a BookmarkName argument for the name of the Bookmark and a NewText argument for the string that replaces the Text property. The code then declares a Range object and sets it to the Bookmark's Range property. Replacing the Range property's Text property also replaces the text in the Bookmark, which is then re-added to the Bookmarks collection:

You can call the procedure by passing the name of the Bookmark and the new text:

When you edit a document in the Word user interface, you probably make extensive use of the Find and Replace commands on the Edit menu. The dialog boxes displayed let you specify search criteria for the text you want to locate. The Replace command is an extension of the Find command, allowing you to replace the searched text.

The Find object is a member of both the Selection and the Range objects, and you can use either one to search for text.

When you use a Selection object to find text, any search criteria you specify are applied only against currently selected text. If the Selection is an insertion point, the entire document will be searched. When the item is found that matches the search criteria, the selection changes to highlight the found item automatically. The following procedure searches for the string "dolor", and when it finds the first one, highlights the word and displays an alert, as shown in Figure 25.

ClearFormatting method prior to each search.There are two different ways to set search options: by setting individual properties of the Find object, or by using arguments of the Execute method. The following procedure illustrates both forms. The first code block sets properties of the Find object and the second code block uses arguments of the Execute object. The code in both code blocks performs the identical search—only the syntax is different. Because you're unlikely to use many of the parameters required by the Execute method, and because you can specify many of the values as properties of the Find object, this is a perfect place for C# developers to create "wrapper" methods, hiding the intricacies of calling the Find.Execute method. This isn't required for Visual Basic developers, but the following example shows off a useful technique for C# developers:

Finding text using a Range object allows you to search for text without displaying anything in the user interface. The Find method returns a Boolean value indicating its results. This method also redefines the Range object to match the search criteria if the text is found. That is, if the Find method finds a match, its range is moved to the location of the match.

The following procedure defines a Range object consisting of the second paragraph in the document. It then uses the Find method, first clearing any existing formatting options, and then searches for the string "faucibus". The code displays the results of the search using the MessageBox.Show method, and selects the Range to make it visible. If the search fails, the second paragraph is selected; if it succeeds, the search criteria is selected and displayed, as shown in Figure 26. The C# version of this example uses the ExecuteFind wrapper method discussed previously.

The Find method also has a Found property, which returns True whenever a searched-for item is found. You can make use of this in your code, as shown in the sample procedure. The code uses a Range object to search for all occurrences of the string "lorem" in the active document, changes the font color and bold properties for each match. It uses the Found property in a loop, and increments a counter each time the string is found. The code then displays the number of times the string was found in a MessageBox. The C# version of this demonstration uses the ExecuteFind method discussed previously.

Find method of a Range variable, Word always updates the Range variable to refer to the found text. If you must retain a reference to the original range, you'll need to keep a second variable that maintains the original information. In this case, because the original range was the entire document, it's easy to get that range reference back later, and there's no need to retain the information in a variable.There are several ways to search and replace text in code. A typical scenario uses the Find object to loop through a document looking for specific text, formatting, or style. If you want to replace any of the items found, you use the Find object's Replacement property. Both the Find object and the Replacement object provide a ClearFormatting method. When you are performing a find and replace operation, you must use the ClearFormatting method of both objects. If you only use it on the Find part of the replace operation, it's likely that you may end up replacing the text with unanticipated options.

You then use the Execute method to replace each found item. The Execute method has a WdReplace enumeration that consists of three additional values: wdReplaceAll: replaces all found items wdReplaceNone: replaces none of the found items wdReplaceOne: replaces the first found item The code in the following procedure searches and replaces all of the occurrences of the string "Lorum" with the string "Forum" in the selection. The C# version of this example uses the ExecuteReplace helper method, modeled after the ExecuteFind method discussed previously:

If you search and replace text in a document, you may want to restore the user's original selection after the search is completed. The code in the sample procedure makes use of two Range objects: one to store the current Selection, and one to set to the entire document to use as a search range. The search and replace operation is then performed and the user's original selection restored. The C# version of this example uses the ExecuteReplace helper method shown previously:

You can display a document in Print Preview mode by setting the active document's PrintPreview property to True:

You can toggle the PrintPreview property of the Application object to display the current document in Print Preview mode. If the document is already in preview mode, it will be displayed in normal view, if it is in normal view, it will be displayed in Print Preview:

You can use the PrintOut method to send a document (or part of a document) to the printer. You can call it from an Application or Document object. The following code fragment prints out the active document with all of the default options:

The PrintOut method has multiple optional arguments that allow you to fine tune how to print the document, as summarized in Table 2.

ArgumentDescriptionBackground

Set to True to allow processing while Word prints the document

Append

Use this with the OutputFileName argument. Set to True to append the specified document to the file name specified by the OutputFileName argument. Set to False to overwrite the contents of OutputFileName.

Range

The page range. Can be any WdPrintOutRange enumeration: wdPrintAllDocument, wdPrintCurrentPage, wdPrintFromTo, wdPrintRangeOfPages, or wdPrintSelection

OutputFileName

If PrintToFile is True, this argument specifies the path and file name of the output file.

From

The starting page number when Range is set to wdPrintFromTo

To

The ending page number when Range is set to wdPrintFromTo

Item

The item to be printed. Can be any WdPrintOutItem enumeration: wdPrintAutoTextEntries, wdPrintComments, wdPrintDocumentContent, wdPrintKeyAssignments, wdPrintProperties, wdPrintStyles

Copies

The number of copies to be printed

Pages

The page numbers and page ranges to be printed, separated by commas. For example, "2, 6-10" prints page 2 and pages 6 through 10.

PageType

The type of pages to be printed. Can be any WdPrintOutPages constant: wdPrintAllPages, wdPrintEvenPagesOnly, wdPrintOddPagesOnly

PrintToFile

Set to True to send printer instructions to a file. Make sure to specify a file name with OutputFileName.

Collate

Use when printing multiple copies of a document. Set to True to print all pages of the document before printing the next copy.

FileName

Available only with the Application object. The path and file name of the document to be printed. If this argument is omitted, Word prints the active document.

ManualDuplexPrint

Set to True to print a two-sided document on a printer without a duplex printing kit.

The following procedure prints out the first page of the active document:

The Tables collection is a member of the Document, Selection, and Range objects, which means that you can create a table in any of those contexts. You use the Add method to add a table at the specified range. The following code adds a table consisting of three rows and four columns at the beginning of the active document:

Once you've created the table, you automatically add it to the Document object's Tables collection and you can then refer to the table by its item number, as shown in the following code fragment:

Each Table object also has a Range property, which allows you to set direct formatting attributes. The Style property allows you to apply one of the built-in styles to the table, as shown in the following code fragment:

Each Table consists of a collection of Cells, with each individual Cell object representing one cell in the table. You refer to each cell by its location in the table. The following code refers to the cell located in the first row and the first column of the table, adding text and applying formatting:

The cells in a table are organized into rows and columns. You can add a new row to a table by using the Add method:

Although you generally define the number of columns when you create a new table, you can also add columns after the fact with the Add method. The following code adds a new column to an existing table, inserting the new column before the existing first column, and then uses the DistributeWidth method to make them all the same width:

The following example creates a Word table at the end of the active document and populates it with document properties:

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有