Understanding The Word Object Model from a .Net Developer's Perspective

xiaoxiao2021-03-06  97

Summary: Provides information on how to use Microsoft Visual Studio Tools for the Microsoft Office System to take advantage of the objects available in Microsoft Office Word 2003. It introduces several important Word objects and provides examples of how to use them You will learn how to. Work With Word 2003 Applications and Documents, AS Well As With Some of The More Important Properties and Methods. (105 Printed Pages)

Download The WordObject.exe from the Microsoft Download Center.

Contents

IntroductionGetting Started with a Word ProjectThe Underpinnings: Documents and TemplatesBird's-Eye View of the Word Object ModelThe Application ObjectThe Document ObjectThe Selection ObjectThe Range ObjectThe Bookmark ObjectSearching and Replacing TextPrintingCreating Word TablesSummary

Introduction

Microsoft® Word is probably one of the most commonly used software products in the world today. Most people using Word get by just fine without writing any code at all, although Word has a rich and powerful object model making it eminently programmable. Microsoft Visual Studio Tools for the Microsoft Office System enables developers to interact with the objects provided by the Microsoft Office Word 2003 object model by using a .NET language, such as Microsoft Visual Basic® .NET or Microsoft Visual C # ®. Word possesses a rich feature set, all of which are accessible through code. There are quite a few objects to learn about, which can be confusing when you're first getting started. Conveniently, Word objects are arranged in a hierarchical fashion, and you can get a good start on the Object Model by Focusing on The Two Main Classes at The Top of the Hierarchy 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 is not anything you can do in the Word user interface that you can not 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 .

Note Programming Word and its objects from Visual Basic .NET feels much like programming in VBA. Visual Basic .NET handles optional parameters, and allows late binding, just like VBA. C #, on the other hand, provides unique challenges when programming against the Word object model. Because C # does not support optional parameters, parameterized properties, or late binding, you'll need to handle many of the Word methods and properties specially when programming in C #. This document points out the differences between Visual Basic .NET and C # programming, as the com up.getting started with a Word Project

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.

Figure 1. You can create Either a Word Document OR a Word Template Project In Visual Studio .NET.

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 incrudes code That Wraps the word.document and word.application objects:

'Visual Basic

Friend Withevents thisDocument as word.document

Friend Withevents thisApplication As Word.Application

// c #

Private word.Application thisapplication = NULL;

Private word.document thisdocument = NULL;

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.

Tip throughout this article, you'll see many buys of the

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, Respective. 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 do not translate well INTO The Object-Oriented Paradigmã,-IT Can Sometimes Be More Convenient To Work Work Work Work Work with you'll want to work with

Option strict on; You'll Learn About The Few Exceptions as The ARISE.

The underpinnings: Documents and Templates

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.

About Normal.dot

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.templates and your code

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.

Figure 2. Procedure References Are Fully Qualified When You Assign The TO A Toolbar.

Tip One thing to remember is that Word always uses the "most local" rule when it comes to templates and documents. If duplicate styles, macros, or any other items exist in all three locationsÃ,Â-Normal.dot, a custom template, And The Current Document â Used First, THE One In Normal.dot.Styles and Formatting

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.

Figure 3. The Default Paragraph Style is Normal.

Modifying styles

When you click on the style name, it turns into a drop-down list box where you can select 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.

Figure 4. MODIFYING A STYLE

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 effect.understanding Paragraph Marks

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 .

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.

Figure 5. The Line Break Does Not Take Paragraph Formatting with it and a paragraph margraph mark does.

Displaying 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.

Figure 6. Displaying Paragraph Marks in The Formatting Marks Section of The Options Dialog Box

Bird's-Eye View of The Word Object Model

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.Figure 7. The Application object contains the Document, Selection, Bookmark, And Range Objects.

The Application Object

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

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

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

. 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's Creates it is running.

.

The Bookmark Object

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.)

Tying it all together

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 .

...............

The Application Object

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.

USING THISAPPLICATION

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 class, you must create a Word Application Object Variable and the crete an instance of word: 'Visual Basic

DIM AppWord as Word.Application = _

New word.Application

// c #

Word.Application Appword = New Word.Application ();

Tip Declaring a

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 do not 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, 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.

Tip the

Thisapplication.ActiveDocument Property, Which Refers to the Active

Document Object, Is Likely the One You'll Use Most Offen. You'll Generally Want To Use

ThisDocument INSTEAD OF

ThisApplication.ActiveDocument syntax.

ActiveDocument Is Available, But you need to flly qualify it with an an

Application Object in Order To Use IT in your code. Using

ThisDocument is more effect as the variable is already create for you, and amouners to the Same.

Application Properties

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 uses the Arrange method of a window object to tile the two windows. Note that the Arrange method uses the WdArrangeStyle then .wdtiled enumerated value. 'Visual Basic

Friend Sub Createnewwindowandtile ()

'Create a New window from the Active Document.

DIM WND As Word.Window = _

Thisapplication.activeWindow.newwindow

'Tile the twoow.

Thisapplication.windows.Arrange (_

Word.wdarRangeStyle.wdtiled)

End Sub

// c #

Public void createnewwindowandtile ()

{

// Create a new window from the Active Document.

Word.window wnd = thisapplication.activeWindow.newwindow ();

// tile the two.

Object value = word.wdarrangestyle.wdtiled;

ThisApplication.windows.Arrange (Ref value);

}

Tip the

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: ' Visual Basic

Friend sub setApplicationcaption ()

'Change Caption in Title Bar.

Thisapplication.caption = "My new capen"

End Sub

// c #

Public void setApplicationCaption ()

{

// Change Caption in Title Bar.

THISAPPLICATION.CAPTION = "My New CAPTION";

}

Capslock: DETERMINES WHETHER CAPSLOCK IS TURNED ON, RETURNINED A Boolean Value. The Following Procedure Displays The State of Capslock: 'Visual Basic

Friend Sub Capslockon ()

Messagebox.show ("Capslock IS" & _

Thisapplication.capslock.tostring ())

End Sub

// c #

Public void capslockon ()

{

Messagebox.show (thisapplication.capslock.toT7tring ());

}

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: 'Visual BasicFriend Sub Displayalerts ()

Try

'Turn Off Display of Messages and Alerts.

Thisapplication.displayalerts = word.wdalertLevel.wdalertsnone

'Your Code Runs Here without Any Alerts.

'. .code doing something.

Finally

'Turn alerts on again.

Thisapplication.displayalerts = word.wdalertlevel.wdalertsall

END TRY

End Sub

// c #

Public void displaphnalerts ()

{

// Turn Off Display of Messages and Alerts.

Try

{

Thisapplication.displayalerts = word.wdalertLevel.wdalertsnone;

// Your Code Runs Here without Any Alerts.

//..................

}

Catch (Exception EX)

{

// Do Something with your exception.

}

Finally

{

// Turn Alerts on again. DONE.

Thisapplication.displayalerts = word.wdalertLevel.wdalertsall;

}

}

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:. 'Visual Basic

Friend Sub Togglestatusbar ()

Dim bln as boolean = (thisapplication.displaystatusbar) thisApplication.displaystatusbar = not BLN

End Sub

// c #

Public void togglestatusbar ()

{

// Toggle Display of The Status Bar.

Bool BLN = thisapplication.displaystatusbar;

Thisapplication.displayStatusbar =! BLN;

}

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. 'Visual Basic

Public Sub ListAllDocFilesonc ()

Dim Str As String

DIM SW As New StringWriter

Try

Thisapplication.system.cursor =

Word.WDCURSORTYPE.WDCURSORWAIT

With thisapplication.filesearch

.Filename = "* .doc"

.Lookin = "c: /"

.SearchSubfolders = true

.Execute ()

For Each Str in .foundFiles

SW.WRITELINE (STR)

NEXT

End with

Messagebox.show (sw.toString ())

Finally

Thisapplication.system.cursor =

Word.WDCURSORTYPE.WDCURSORNORMAL

END TRY

End Sub

// c #

Public void ListallDocFilesonc ()

{

Try

{

Thisapplication.system.cursor = word.wdcursortype.wdcursorwait;

StringWriter SW = new stringwriter ();

Office.FileSearch fs = thisapplication.filesearch;

fs.FileName = "* .doc";

fs.lookin = "c: //";

Fs.searchsubfolders = true;

// Select The Defaults, Optional in VBA:

fs.execute (office.msosortby.msosortbyfilename,

Office.msosortorder.msosortordOroscending, true);

Foreach (String str in fs.foundfiles)

{

SW.WRITELINE (STR);

}

Messagebox.show (sw.toString ());

}

Finally

{

Thisapplication.system.cursor =

Word.WDCURSORTYPE.WDCURSORNORMAL;

}

}

Tip In this example, you'll note that Visual Basic .NET developers need not pass all the parameters to theExecute 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 had not passed a value at all. For value-type parameters, you .

PATH: WHEN Used with the application Object, returns the path of the current application: 'Visual Basic

Messagebox.show (thisapplication.path)

// c #

MessageBox.show (thisapplication.path);

Tip to return the path of the activity document, use thisdocument.path.

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 Automatical Updated, and Hidden Text And Field Codes Will Be Printed. 'Visual Basic

'Set Various Application Options

With thisapplication.option.Option

. Backgroundsave = TRUE

.OverType = True

.Updatefieldsatprint = true

.Printhiddentext = true

.Printfieldcodes = true

End with

// c #

// set Various Application Options.

Word.Options Options = thisapplication.options;

Options.Backgroundsave = true;

Options.Overtype = true;

Options.Updatefieldsatprint = true; options.printhiddentext = true;

Options.printfieldcodes = true;

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 the restaurant the original username. 'Visual Basic

Friend subs changingusername ()

Dim Str as string = thisapplication.username

Messagebox.show (STR)

'Change Username.

Thisapplication.username = "Dudley"

Messagebox.show (thisapplication.username)

'Restore Original Username.

Thisapplication.username = STR

End Sub

// c #

Public void changeUsername ()

{

String str = thisapplication.username;

Messagebox.show (STR);

// Change username.

Thisapplication.username = "dudley";

MessageBox.Show (thisapplication.username);

// restore Original UserName.

ThisApplication.username = STR;

}

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: 'Visual Basic

Try

Thisapplication.visible = false

'Do Work here, Invisibly.

Catch exception

'Your Exception Handler Here.Finally

Thisapplication.visible = TRUE

END TRY

// c #

Try

{

THISPPLICATION.Visible = FALSE;

// DO wherever it is, invisibly.

}

Catch (Exception EX)

{

// Your Exception Handler Here.

}

Finally

{

THISAPPLICATION.Visible = true;

}

Application Methods

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 the. The follow code checks the string" spellel "and displays false in a messagebox. 'Visual Basic

Friend Sub SpellCheckstring ()

'Checks a specified string for spelling errors.

DIM STR AS STRING = "Speling Erors here."

IF thisapplication.checkspelling (str) THEN

Messagebox.show (String.Format ("No Errors in" {0} "" ", str))

Else

Messagebox.show (String.Format)

"" {0} "" is spelled incorrectly ", str))

END IF

End Sub

// c #

Public void SpellCheckstring ()

{

// Checks a specified string for spelling errors.

String str = "speling errs";

Object CustomDictionary = type.missing;

Object ignoreuppercase = type.missing;

Object mainDictionary = type.missing;

Object CustomDictionary2 = type.missing; Object CustomDictionary3 = Type.Missing;

Object CustomDictionary4 = type.missing;

Object CustomDictionary5 = type.missing;

Object CustomDictionary6 = type.missing;

Object CustomDictionary7 = type.missing;

Object CustomDictionary8 = type.missing;

Object CustomDictionary9 = type.missing;

Object CustomDictionary10 = Type.Missing;

// the checkspelling method taket a lot of optional

// Parameters, in VBA:

IF (Thisapplication.checkspelling (Str, Ref CustomDictionary,

Ref IgnoreUppercase, Ref Maindictionary, Ref CustomDictionary2,

Ref CustomDictionary3, Ref CustomDictionary4,

Ref CustomDictionary5, Ref CustomDictionary6,

Ref CustomDictionary7, Ref CustomDictionary8,

Ref CustomDictionary9, Ref CustomDictionary10))))

{

Messagebox.show (String.Format ("No ErrorS IN /" {0} / "" "" ", STR));

}

Else

{

Messagebox.show

String.Format ("/" {0} / "is spelled incorrectly", str);

}

}

Tip this Example Demonstrates Another Example In Which Visual Basic .Net Developers have it much easier trose development in c #. The

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: 'Visual Basic

Friend Sub DisplayHelPabout ()

Thisapplication.Help (Word.wdhelptype.wdhelpabout)

End Sub

// c #

Public void displayhelpabout ()

{

Object value = word.wdhelptype.wdhelpabout;

ThisApplication.Help (Ref value);

}

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: 'Visual Basic

Friend Sub MoveandResizeWindow ()

'None of this Will Work if the window is maximized

'or minimized.

Thisapplication.activeWindow.WindowState = _

Word.windWindowState.wdWindowStatenormal

'Position at Upper Left Corner.

Thisapplication.move (0, 0)

'Size to 300 x 600 Points.

Thisapplication.resize (300, 600)

End Sub

// c #

Public void moveandresizeWindow ()

{

// none of this will work if the window is

// maximized or minimized.

ThisApplication.activeWindow.windowState =

Word.wDwindowState.wdwindowsTatenormal;

// Position At Upper Left Corner.

THISAPPLICATION.MOVE (0, 0);

// size to 300 x 600 Points.

ThisApplication.resize (300, 600);

}

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: 'Visual Basic' Automatically save changes.

Thisapplication.quit (Word.WDsaveOptions.wdsaveChanges)

'Prompt to save change.

Thisapplication.quit (Word.wdsaveOptions.wdprompttosavechanges)

'Quit With Saving Changes.

Thisapplication.quit (Word.wdsaveOptions.wddonotsavechanges)

// c #

// Automatically Save Changes.

Object savechanges = word.wdsaveoptions.wdsavechange;

Object OriginalFormat = type.missing;

Object routedocument = type.missing;

Thisapplication.quit (Ref Savechanges,

Ref originalformat, ref routedocument;

// Prompt to save change.

SaveChanges = Word.wdsaveOptions.wdpromptomptosavechange;

OriginalFormat = type.missing;

ROUTEDocument = type.missing;

Thisapplication.quit (Ref Savechanges,

Ref originalformat, ref routedocument;

// quit welking.

Savechanges = word.wdsaveoptions.wddonotsavechange;

OriginalFormat = type.missing;

ROUTEDocument = type.missing;

Thisapplication.quit (Ref Savechanges,

Ref originalformat, ref routedocument;

Tip the

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 by reference by reference by reference by reference by reference

Sendfax: Launches The Fax Wizard, AS Shown in Figure 8. The user can death the Operation. 'Visual Basic

Friend Sub Launchfaxwizard ()

Thisapplication.sendfax ()

End Sub

// c #

Public void launchfaxwizard ()

{

THISPPLICATION.SENDFAX ();

}

Figure 8. The fax wizard can be launched by the sendfax method.

USING THE Built-in Dialog Boxes in Word

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.:

'Visual Basic

DIM DLG AS WORDIALOG

// c #

Word.Dialog DLG;

To Specify THE WORD DIALOG You're Intested in, Assign The Variable To One of the Values ​​Returned from The Array of Available Dialogs:

'Visual Basic

DLG = thisApplication.dialogs (Word.wdwordDialog.wddialogfilenew)

// c #

DLG = thisApplication.dialogs [word.wdworddialog.wddialogfilenew];

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..:

'Visual Basic

Friend Sub DisplayFilenewDialog ()

DIM DLG AS WORDIALOG

DLG = thisapplication.dialogs (_

Word.wdwordDialog.wddialogfilenew)

Dlg.show ()

End Sub

// c #

Public void displayFilenewdialog ()

{

Object timeout = type.missing;

Word.Dialog DLG;

DLG = thisApplication.dialogs [word.wdworddialog.wddialogfilenew];

DLG.SHOW (Ref Timeout);

}

Tip the

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:

'Visual Basic

Friend Sub DisplaySpellCheckDialog ()

DIM DLG AS WORDIALOG

DLG = thisapplication.dialogs (_

Word.wdwordDialog.wddialogtoolsspellingandgrammar)

Dlg.show ()

End Sub

// c #

Public void displayspellcheckdialog ()

{

Object timeout = type.missing;

Word.Dialog DLG;

DLG = thisApplication.dialogs

[Word.wdworddialog.wddialogtoolsspellingandgrammar];

DLG.SHOW (Ref Timeout);

}

Word.Dialog Methods

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:. 'Visual Basic

Friend Sub DisplayUserInfodialog ()

DIM DLG AS WORDIALOG

DLG = thisapplication.dialogs (_

Word.wdwordDialog.wddialogtoolsoptionsuserInfo)

Dlg.display (3000)

End Sub

// c # public void displayuserinfodialog ()

{

Word.Dialog DLG;

Object timeout = 3000;

DLG = THISAPPLICATION.DIALOGS [

Word.wdwordDialog.wddialogtoolsoptionsuserInfo];

Dlg.display (Ref Timeout);

}

Tip although it's tempting for c # developers to attempt to pass Literal Parameters as Simple Parameters, Doing So Will Make your code not compile. Instead, c # developers Must Create AN

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, the user copy their changes to be saved, and if the click The can be here..

'Visual Basic

DIM RETURNVALUE AS INTEGER = DLG.DISPLAY ()

// c #

Integer returnValue = dlg.display ();

The Possible Return Values ​​Are Displayed in Table 1:

Table 1. Command Button Return Values

ValueButton Clicked-2The Close Button-1The Ok Button0 (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 does not 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 will not 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)

DIM DLG AS WORDIALOG

DLG = thisapplication.dialogs (_

Word.wdwordDialog.wddialogtoolsoptionsuserInfo)

'Wait 10 Seconds for Results.

DIM INT As INTEGER = DLG.DISPLAY (10000)

'DID THE USER PRESS OK?

IF INT = -1 Then

Dlg.execute ()

END IF

End Sub

// C #

Public void displayexecutedialog ()

{

Word.Dialog DLG;

DLG = THISAPPLICATION.DIALOGS [

Word.wdwordDialog.wddialogtoolsoptionsuserInfo];

// Wait 10 Seconds for Results.

Object timeout = 10000;

Int value = dlg.display (ref timeout);

// DID THE USER PRESS OK?

IF (value == -1)

{

Dlg.execute ();

}

}

Tip you can retrieve the name value entered in the userinfo dialog box using the

Thisapplication.username.

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.) Modifying Dialog Values

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:

'Visual Basic

DIM DLG AS WORDIALOG

DLG = thisapplication.dialogs (_

Word.wdwordDialog.wddialogfilepagesetup)

DLG.PageWidth = 3.3

DLG.PageHeight = 6.6

Unfortunately, this Code Simply Won't compile in Visual Basic .NET with OPTION STRICT SET ON, OR IN C # at all-the pageHe PageTies 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'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:

'Visual Basic

DLG = thisapplication.dialogs (_

Word.wdwordDialog.wddialogfilepagesetup)

CallbyName (DLG, "PageWidth", CallType.let, 3.3)

CallbyName (DLG, "PageHeight", CallType.let, 6)

// C #

Using vb = microsoft.visualbasic;

// Then, WITHIN Some Procedure:

DLG = thisApplication.dialogs

[Word.wdworddialog.wddialogfilepagesetup];

Vb.interaction.callbyname (DLG, "PageWidth",

Vb.calltype.let, 3.3);

Vb.interaction.callbyname (DLG, "PageHeight",

Vb.calltype.let, 6);

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 Uout Requiring You To Dig Around Into Multiple Objects:

'Visual Basic

Using vb = microsoft.visualbasic;

Public Sub HiddenpageSetupDialog ()

DIM DLG AS WORDIALOG

DLG = thisapplication.dialogs (_

Word.wdwordDialog.wddialogfilepagesetup)

CallbyName (DLG, "PageWidth", CallType.let, ConvertToInches (3.3))

CallbyName (DLG, "PageHeight", CallType.let, ConvertToInches (6))

Callbyname (DLG, "Topmargin", CallType.let, ConvertToInches (0.72))

CallbyName (DLG, "Bottommargin", CallType.let, _

CONVERTTOINCHES (0.72))

CallbyName (DLG, "Left Margin", CallType.let, _

CONVERTTOINCHES (0.66))

CallbyName (DLG, "Right Margin", CallType.let, _

CONVERTTOINCHES (0.66))

CallbyName (DLG, "Orientation", CallType.let, _

Word.wdorientation.wdorientportrait)

CallbyName (DLG, "DifferentfirstPage", CALLTYPE.LET, FALSE

CallbyName (DLG, "HeaderDistance", CallType.let, _

CONVERTTOINCHES (0.28))

'Use the applypropsto protety to determine where

'The property settings areatically applie

'0 = this section

'1 = this point forward' 2 = SELECTED SECTIONS

'3 = SELECTED TEXT

'4 = WHOLE Document

CallbyName (DLG, "ApplyPropsto", CALLTYPE.LET, 0)

Dlg.execute ()

End Sub

Private function convertToinches (byval value as double) AS String

Return string.format ("{0}" ", value)

END FUNCTION

// C #

Public void hiddenpagesetupdialog ()

{

Word.Dialog DLG;

DLG = THISAPPLICATION.DIALOGS [

Word.wdwordDialog.wddialogfilepagesetup];

Vb.interaction.callbyname (DLG, "PageWidth", vb.calltype.let,

CONVERTTOINCHES (3.3));

Vb.interaction.callbyname (DLG, "PageHeight", vb.calltype.let,

CONVERTTOINCHES (6));

Vb.interaction.callbyname (DLG, "TopMargin", vb.calltype.let,

CONVERTTOINCHES (0.72));

Vb.interaction.callbyName (DLG, "Bottommargin", vb.calltype.let,

CONVERTTOINCHES (0.72));

Vb.interaction.callbyname (DLG, "Left Margin", vb.calltype.let,

CONVERTTOINCHES (0.66));

Vb.interaction.callbyname (DLG, "Right Margin", vb.calltype.let,

CONVERTTOINCHES (0.66));

Vb.interaction.callbyname (DLG, "orientation", vb.calltype.let,

Word.wdorientation.wdorientPortrait);

Vb.interaction.callbyname (DLG, "DiffERENTFIRSTPAGE",

Vb.calltype.let, false);

Vb.interaction.callbyname (DLG, "HeaderDistance", vb.calltype.let,

CONVERTTOINCHES (0.28));

// use the applypropsto property to determine where

// the property settings areatically applied:

// 0 = this section

// 1 = this Point Forward

// 2 = SELECTED SECTIONS

// 3 = SELECTED TEXT

// 4 = WHOLE Document

Vb.interaction.callbyName (DLG, "ApplyPropsto", Vb.CallType.let,

0);

Dlg.execute ();

}

Private String ConvertToInches (Double Value)

{

Return string.format ("{0} /" ", value);

Tip The use of measurements in Word can be confusing at times. Most measurements in Word contain values ​​in points (1/72 "), but you can always override the units by passing a string, like" 3 "" to indicate three inches. The Sample Includes the

ConvertToInches Method, Which Handles Tacking on The next the nextary quote mark. The odd thing is what

PageWidth and

PageHeight Properties 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 IHEREFORE UNNEESSARY, IN Countries That Use Inches by Default, for The First Two Properties In 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.

Tip if you want to make full!

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 Document Object

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 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

Document Object Collectes

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

Referencing Documents

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 FRAGENT STS An Object Variable To Refer to The First Document Object In The Documents Collection:

'Visual Basic

DIM DOC AS WORD.Document = _

Directcast (thisApplication.documents (1), word.document)

// C #

Word.Document doc = (Word.Document) ThisApplication.Documents [1]; 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".:

'Visual Basic

DIM DOC AS WORD.Document = _

Directcasts (thisapplication.documents), word.document)

// c #

Word.Document doc =

(Word.Document) thisapplication.documents ["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 Effectient Reference When You Need To Refer to The Document That Has The Focus. The Following Code Fragment Retrieves The Name of The Active Document:

'Visual Basic

Dim Str As string = thisdocument.name

// c #

String str = thisDocument.name;

Opening, Closing, and Creating New Documents

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.

CREANG A New Word Document

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. 'Visual Basic

'Create a new document based on normal.dot.

Thisapplication.documents.add ()

// c #

// Create a new document based on normal.dot.

Object Template = type.missing;

Object newTemplate = type.missing;

Object DocumentType = Type.Missing;

Object visible = type.missing;

Thisapplication.documents.add (

Ref Template, Ref newTemplate, Ref documentType, Ref Visible

Tip the

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.

Template Argument to create a new docuher tour.. You need to supply the full the template can be found.

'Visual Basic

'Create a New Document Based on a Custom Template.

Thisapplication.documents.add (_

"C: /test/mytemplate.dot")

// c #

// CREATE A New Document Based on a custom template.

Object Template = @ "c: /test/mytemplate.dot";

Object newTemplate = type.missing;

Object DocumentType = Type.Missing;

Object visible = type.missing;

Thisapplication.documents.add (

Ref Template, Ref newTemplate, Ref documentType, Ref Visible

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 confusedhen it comes to choosing the correct template.opening an existing document

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 FileNameter:

'Visual Basic

Thisapplication.documents.open ("c: / test / mynewdocument))

// c #

Object filename = @ "c: / test / mynewdocument";

Object confirmconversions = type.missing;

Object readonly = type.missing;

Object addtorecentfiles = type.missing;

Object passworddocument = type.missing;

Object passwordTemplate = type.missing;

Object repert = type.missing;

Object writepassworddocument = type.missing;

Object writepasswordTemplate = type.missing;

Object Format = type.missing;

Object encoding = type.missing;

Object visible = type.missing;

Object openconflictdocument = type.missing;

Object Openandrepair = type.missing;

Object DocumentDirection = Type.Missing;

Object noencodingDialog = type.missing; thisapplication.documents.open (Ref filename,

Ref confirmconversions, ref readonly, ref addttorecentfiles,

Ref PasswordDocument, Ref PasswordTemplate, Ref Revert,

Ref writepassworddocument, ref writepasswordTemplate,

Ref format, ref encoding, ref visible, ref openconflictdocument,

Ref opeNandrepair, Ref DocumentDirection, Ref NoEncodingDialog;

Saving Documents

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' Visual Basic

ThisApplication.documents.save ()

// C #

Object noPrompt = type.missing;

Object OriginalFormat = type.missing;

ThisApplication.documents.save (Ref noPrompt, Ref OriginalFormat);

The Following Code Sets The NoPt Parameter To True, and Saves All Open Documents WITHOUT User Intervention. 'Visual Basic

Thisapplication.documents.save (noPrompt: = true)

// C #

Object noPROMPT = TRUE;

Object OriginalFormat = type.missing;

ThisApplication.documents.save (Ref noPrompt, Ref OriginalFormat);

Tip The Default Value Fornoprompt 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 Saveing ​​Document Object. The Following Code Fragment Shows Two Ways to Save The Active Document: 'Visual Basic

'Save the Active Document.

ThisDocument.save ()

'OR

Thisapplication.activeDocument.save ()

// c #

// Save the Active Document.

ThisDocument.save ();

// OR

ThisApplication.ActiveDocument.save ();

IF you're not Sure is The aific, you can refer to it by its name. This code uses the save method on a named document. 'Visual Basic

ThisApplication.documents ("MynewDocument.doc"). Save ()

// c #

Object file = "mynewdocument.doc";

THISAPPLICATION.Documents.get_Item (ref file) .save ();

Tip although Visual Basic .Net Developers Can Retrieve Items from the Various Collections Using The Standard Visual Basic Syntax (Calling The

Item Property, or Leaving Out this OPTIONAL CALL, And Supplying An Index or Name, C # Developers Generally Cannot. Instead, C # developers generally must call

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 To

Get_item method.

An alternate syntax would be to use the document's index number, although that is not as reliable for two reasons. The first is that you can not be sure which document is being referred to since the index number can change, and the second is that if the referenced document has not been saved yet the save dialog box will appear The following code saves the first document in the Documents collection:. 'Visual BasicThisApplication.Documents (1) .Save ()

// c #

Object file = 1;

THISAPPLICATION.Documents.get_Item (ref file) .save ();

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 #.) 'Visual Basic

'Save The Document. In a real application,

'You'd Want to Test to See If THE FILE

'Already Exists. This Will Overwrite Any Previously

'existing document with the specified name.

ThisDocument.saveas ("c: /test/mynewdocument.doc")

// c #

// Save the document. In a real application,

// You'D Want to Test to See if the file

// already exists. this will overwrite annoupefiously

// EXISTING DOCUMENTS.

Object filename = @ "c: /test/mynewdocument.doc";

Object fileformat = type.missing;

Object Lockcomments = type.missing;

Object password = type.missing;

Object addtorecentfiles = type.missing;

Object writepassword = type.missing;

Object readOrthlyRecommended = type.missing; object embedtrueTypefonts = type.missing;

Object SavenativePictureFormat = Type.missing;

Object saveformsdata = type.missing;

Object Saveasaocletter = Type.Missing;

Object encoding = type.missing;

Object insertlinebreaks = type.missing;

Object allowsubstitutions = type.missing;

Object linending = type.missing;

Object addbidimarks = type.missing;

ThisDocument.saveas (Ref FileName, Ref FileFormat, Ref Lockcomments,

Ref Password, Ref addtorecentfiles, Ref writepassword,

Ref readonlyrecommended, Ref EmbedtruETrueTypefonts,

Ref SavenativePictureFormat, Ref SaveFormsData,

Ref Saveasaocletter, Ref Encoding, Ref InsertLineBreaks,

Ref allowsubstitutions, ref lineending, ref addbidimarks;

Closing Documents

The close method can be used to save docuod.

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' Visual Basic..

Thisapplication.documents.close ()

// c #

Object savechanges = type.missing;

Object OriginalFormat = type.missing;

Object routedocument = type.missing;

Thisapplication.documents.close (Ref Savechange,

Ref originalformat, ref routedocument;

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: 'Visual Basic

'Closes All Documents: Saves with no prompt.thisapplication.documents.close (_

Word.wdsaveOptions.wdsavechanges)

'Closes All Documents: Does Not Save Any Changes.

Thisapplication.documents.close (_

Word.wdsaveOptions.wddonotsaveChanges)

// c #

// Closes All Documents: Saves with no prompt.

Object savechanges = word.wdsaveoptions.wdsavechange;

Object OriginalFormat = type.missing;

Object routedocument = type.missing;

Thisapplication.documents.close (Ref Savechange,

Ref originalformat, ref routedocument;

// Closes All Documents: Does Not Save Any Changes.

Object savechanges = word.wdsaveoptions.wddonotsavechange;

Object OriginalFormat = type.missing;

Object routedocument = type.missing;

Thisapplication.documents.close (Ref Savechange,

Ref originalformat, ref routedocument;

Note when you call the

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 Down.

Close A Single Document: The Covements listed here close The Active Document WITHOUT SAVING CHANGES: 'Visual Basic

'Close The Active Document without saving change.

ThisDocument.close (_

Word.wdsaveOptions.wddonotsaveChanges)

'Close MynewDocument and Save Changes WITHOUT PROMPTING.

ThisApplication.documents ("MyNewDocument.doc"). Close (_ _

Word.wdsaveOptions.wdsavechanges)

// c #

// Close The Active Document without saving change.

Object savechanges = word.wdsaveoptions.wddonotsavechange;

Object OriginalFormat = type.missing;

Object routedocument = type.missing;

ThisDocument.close (Ref Savechanges, Ref Routedocument);

// Close MynewDocument and save change..

Object name = "mynewdocument.doc";

Savechanges = word.wdsaveOptions.wdsavechange;

OriginalFormat = type.missing;

ROUTEDocument = type.missing;

Word.Document doc = thisApplication.documents.get_item (ref name);

ThisDocument.close (Ref Savechanges,

Ref originalformat, ref routedocument;

Looping through the documents collection

Most of the time you probably are not 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 Open Documents, Andiff, Saves Iten 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 has not 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

'Visual Basic

Public Sub searchUnsavedDocuments ()

'Iterate Through The Documents Collection.

Dim Str As String

DIM DOC AS WORD.Document

DIM SW As New StringWriter

For Each Doc in thisapplication.documentsif Not Doc.saved THEN

'Save the document.

Doc.save ()

SW.WRITELINE (Doc.name)

END IF

NEXT

Str = sw.toString ()

IF str = string.empty then

Str = "No Documents Need Saving."

END IF

Messagebox.show (Str, "SaveunsavedDocuments)

End Sub

// c #

Public void saveunsaveddocuments ()

{

// Iterate Through The Documents Collection.

String Str;

StringWriter SW = new stringwriter ();

Foreach (Word.Document Doc in thisApplication.documents)

{

IF (! doc.saved)

{

// Save the document.

Doc.save ();

SW.WRITELINE (Doc.name);

}

}

Str = sw.toString ();

IF (str == String.empty)

{

Str = "no docuuments need saving."

}

Messagebox.show (Str, "SaveunsavedDocuments);

}

The Selection Object

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. 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.

Note the

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.

Tip Be wary of modifying the user's selection, using theSelection object. If you need to work with a portion of the document but do not want to modify the user's selection, use a specific range, paragraph, sentence, and so on.

Using the Type Property

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 successd 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 does not 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:

'Visual Basic

Friend Sub showselectionType ()

Dim Str As String

Select Case thisApplication.seection.typecase word.wdselectionType.wdselectionBlock

Str = "block"

Case word.wdselectiontype.wdselectioncolumn

Str = "column"

Case word.wdselectiontype.wdselectionframe

Str = "frame"

Case word.wdselectiontype.wdselectioninlineshape

Str = "inline shape"

Case word.wdselectiontype.wdselectionip

Str = "Insertion Point"

Case word.wdselectiontype.wdselectionnormal

Str = "Normal Text"

Case word.wdselectiontype.wdnosection

Str = "no selection"

Case word.wdselectiontype.wdselectionRow

Str = "row"

Case Else

Str = "(unknown)"

End SELECT

MessageBox.show (Str, "ShowSelectionType")

End Sub

// c #

Public void showselectionType ()

{

String Str;

Switch (thisapplication.selection.type)

{

Case word.wdselectionType.wdseectionBlock:

Str = "block";

Break;

Case word.wdselectionType.wdselectionColumn:

Str = "column";

Break;

Case word.wdselectiontype.wdselectionframe:

Str = "frame";

Break;

Case word.wdseelectiontype.wdselectioninlineshape:

Str = "inline shape";

Break;

Case word.wdselectiontype.wdseectionip:

Str = "Insertion Point";

Break;

Case word.wdselectiontype.wdselectionnormal:

Str = "normal text";

Break;

Case word.wdselectionType.wdnosection:

Str = "no selection";

Break;

Case word.wdselectiontype.wdselectionRow:

Str = "row";

Break;

DEFAULT:

Str = "(unknown)";

Break;

}

Messagebox.show (Str, "ShowSelectionType");

}

Navigating and successing text

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.Home and End Key Methods

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 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.

You Use ONE FOLLOWING WDMOVEMENTTYPE ENUMERATIONS for the Extend Argument, Which Determines WHETER 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 o f 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.:

'Visual Basic

'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);

Arrow Key Methods

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 ENUMEFT AND MOVERHT:

WDCHARACTER: Move In Character Increments. Wdword: Move In Word Increments. wdcell: Move In Cell Inly. wdsencept: Move Insence Increments.

The Following Code Fragment Moves The Insert To The Left Three Characters, and The Reeds The Three Words To The Right of The Insertion Point.

'Visual Basic

'Move The Insertion Point Left 3 Characters.

Thisapplication.selection.moveleft (_

Word.wdunits.wdcharacter, 3, _

Word.wdmovementType.WDMOVE)

'Select the 3 Words to the right of the insertion point.

ThisApplication.selection.moveright (_ _

Word.wdunits.wdword, 3, _

Word.wdmovementType.wdextend)

// c #

//Move the insertion point left 3 character.

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. 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.

'Visual Basic

'Move The Insertion Point Up ONE LINE.

Thisapplication.selection.moveup (_

Word.wdunits.wdline, 1, Word.wdmovementType.wdmove)

'Select The Following 3 paragraphs.

Thisapplication.selection.movedown (_

Word.wdunits.wdparagraph, 3, Word.wdmovementType.wdmove)

// c #

//Move the insertion point up one line.

Object unit = word.wdunits.wdline;

Object count = 1;

Object Extend = Word.wdmovementType.wdmove;

ThisApplication.selection.moveup (Ref unit, ref count, ref extend);

// Select the folowing 3 paragraphs.

Unit = word.wdunits.wdparagraph;

count = 3;

Extend = word.wdmovementtype.wdmove;

Thisapplication.selection.movedown (Ref Unit, Ref Count,

Ref extend;

The Move Method

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 ITSELF: 'Visual Basic

Thisapplication.selection.move (Word.WDUnits.wdword, 3)

// c #

// use the move method to move 3 words.

Obiect unit = word.wdunits.wdword;

Object count = 3;

ThisApplication.selection.move (Ref unit, ref count);

INSERTING TEXT

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 actid, any text next to the insertion point will be overwritten:

'Visual Basic

Friend Sub InsertTexturation ()

Dim sln as word.selection = thisapplication.selection

'Make Sure Overtype is turned off.

Thisapplication.Options.Overtype = false

// c #

Public void inserttexturation ()

{

Word.seection sln = thisapplication.selection;

// make Sure Overtype is Turned Off.

THISPPLICATION.Options.Overtype = FALSE;

The current selection is an insertion point. If it is is, the code inserts asence using typext, and then a paragraph maark by useing the typeparagraph method:

'Visual Basic

With SLN

'Test to see if selection is an insertion point.

If .type = word.wdselectiontype.wdselectionip then

.Typetext ("Inserting at INSERTION POINT.")

.Typeparagraph () // c #

// Test to see if Selection an insertion point.

IF (sln.type == word.wdselectiontype.wdselection)

{

Sln.Typetext ("Inserting Atsertion Point.");

Sln.TypeParagraph ();

}

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 marg are life

'Visual Basic

Elseif.type = word.wdselectiontype.wdselectionnormal dam

'Move to Start of Selection.

IF thisApplication.Options.replaceselection then

.Collapse (word.wdcollapsedirection.wdcollapsestart)

END IF

.Typetext ("Inserting Before A Text Block.")

.TypeParagraph ()

Else

'Do nothing

END IF

End with

End Sub

// c #

Else if (sln.type == word.wdselectiontype.wdselectionnormal)

{

// Move to start of selection.

Thisapplication.Options.ReplaceSelection

{

Object direction = word.wdcollapsedirection.wdcollapsestart;

Sln.collapse;

}

SLN.TYPETEXT ("Inserting Before A Text Block.");

Sln.TypeParagraph ();

}

Else

{

// do nothing.

}

}

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

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 Includedes All Non-Printing Characters, Such As Spaces, Tabs, and Paragraph Marks.note The Ranges You Create Aren't ONLY IN Existence As Long As your code is running.

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 does not 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.

DEFINING AND SELECTING A RANGE

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. 'Visual Basic

DIM RNG As Word.Range = thisdocument.range (0, 7)

RNG.select ()

// c #

Object start = 0;

Object end = 7;

Word.Range RNG = thisDocument.range (Ref start, ref end);

RNG.select ();

Figure 9 Shows The Results, Which include the paragraph mark and a space.

Figure 9. A Range Object Includes Non-Printing Characters.

Counting characters

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:

'Visual Basic

DIM RNG As Word.Range = _

ThisDocument.range (0, thisdocument.characters.count)

'Or use:

'RNG = thisdocument.range ()

RNG.select ()

Messagebox.show (_

"Characters:" & thisDocument.characters.count.toString)

// c #

Object start = type.missing;

Object End = type.missing;

Word.Range RNG = thisDocument.range (Ref start, ref end);

RNG.select ();

Messagebox.show ("Characters:"

ThisDocument.characters.count.toString ()); TIP in Visual Basic .NET, CALLING THE

Range method without any parameters returns the entire range-you need not specify the start and end values ​​if you simply want to work with the entire contents of the document. This does not 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.

Setting Up Ranges

IF you don't care about you want to do is to select the entire document, you can use the document Object's SELECT METHOD ON ITS Range property

'Visual Basic

ThisDocument.range.select ()

// c #

Object start = type.missing;

Object End = type.missing;

Word.Range RNG = thisDocument.range (Ref start, ref end);

RNG.select ();

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:

'Visual Basic

DIM RNG As Word.Range = thisDocument.content

RNG.select ()

// c #

Word.Range rng = thisdocument.content;

You can also use the method:

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

'Visual Basic

Friend Sub Selectsence ()

Dim rng as word.rangewith thisdocument

If.sentes.count> = 2 THEN

'Supply A Start and End Value for the Range.

RNG = .range (_

Ctype (.sentes (2) .start, system.object, _

Ctype (.sentes (2) .end, system.object))

'Select the Range.

RNG.select ()

END IF

End with

End Sub

// C #

Public void selectsence ()

{

Word.range RNG;

IF (thisDocument.sentences.count> = 2)

{

// Supply a start and end value for the range.

Object start = thisdocument.sentences [2] .start;

Object end = thisdocument.sentences [2].

RNG = thisDocument.range (ref start, ref end);

RNG.select ();

}

}

Note the parameters passed to the parameters

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.

Tip unlike the

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.:

'Visual Basic

DIM RNG As Word.Range = thisdocument.sentes (2)

RNG.select ()

// c #

Word.Range RNG = thisDocument.sentes [2];

RNG.select ();

EXTENDING A RANGE

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 WDPARAGRAGRAGRAGRABL 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 ............................

'Visual Basic

'Define a Range of 7 Characters.

DIM RNG As Word.Range = _

ThisDocument.Range (0, 7)

'Move The Starting Position 7 Characters.

RNG.MoveStart (Word.wdunits.wdcharacter, 7)

'Move the ending position 7 character.

RNG.Movend (Word.WDUnits.wdcharacter, 7)

// c #

// define a Range of 7 Characters.

Object start = 0;

Object end = 7;

Word.Range RNG = thisDocument.range (Ref start, ref end);

//Move the starting position 7 character.

Object unit = word.wdunits.wdcharacter;

Object country = 7;

RNG.MOVESTART (Ref Unit, ref count);

//Move the ending position 7 character.

Unit = word.wdunits.wdcharacter;

count = 7;

RNG.Movend (Ref Unit, Ref Count);

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 Movend Statement Moves The End of The Range by Seven Characters.figure 10. Using The MoveStart and Movend Methods To Resize A Range

Retrieving Start and End Characters in a Range

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:

'Visual Basic

Messagebox.show (String.Format)

"START: {0}, end: {1}", rng.start, rng.end, _

"Range Start and End")

// c #

Messagebox.show (String.Format ("Start: {0}, end: {1}",

RNG.START, RNG.END, "Range Start and End";

Using set to reset A Range

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:

'Visual Basic

DIM RNG As Word.Range

RNG = thisDocument.range (0, 7)

'Reset the existing range.

RNG.SetRange (_

ThisDocument.sentes (2) .start, _

ThisDocument.sentes (5) .end)

// c #

Word.range RNG;

Object start = 0;

Object end = 7;

RNG = thisDocument.range (ref start, ref end);

// reset the existing range.

RNG.SetRange (thisDocument.sentes [2] .start,

ThisDocument.sentes [5].

RNG.select ();

Formatting text

You can also used. The steps you need to take in your code area: define the ing to format. Apply the formatted. 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 Und Code Block Applies The Normal Indent Style and Displays a Messagebox to Pause The Code. The Calls a MessageBox.

'Visual Basic

Friend Sub FormatRangeandundo ()

'Set the Range to The First Paragraph.

DIM RNG As Word.Range = _

ThisDocument.Paragraphs (1). Range

'Change the formatting.

WITH RNG

.FONT.SIZE = 14

.Font.name = "arial"

.Paragraphformat.Alignment = _

Word.WDPARAGRAGRIGNMENT.WDALIGNPARAGRAPHCENTER

End with

RNG.select ()

MessageBox.show ("Formatted Range", "FormatRangeandundo")

'Undo The Three Previous Actions.

ThisDocument.undo (3)

RNG.select ()

MessageBox.show ("Undo 3 Actions", "FormatRangeandundo")

'Apply the Normal Indent Style.

RNG.Style = "Normal Indent"

RNG.select ()

Messagebox.show ("Normal Indent Style Applied",

"FormatRangeandundo")

'Undo a single action.

ThisDocument.undo ()

RNG.select ()

MessageBox.show ("undo 1 action", "formatrangeandundo")

End Sub

// c #

Public Void FormatRangeandundo ()

{

// set the Range to the First Paragraph.

Word.Range RNG = thisdocument.Paragraphs [1] .range;

// Change the formatting.

RNG.FONT.SIZE = 14;

RNG.FONT.NAME = "arial";

RNG.PARAGRAPHFORMAT.Alignment =

Word.wdparagraphalignment.wdalignparagraphCenter;

RNG.select ();

Messagebox.Show ("Formatted Range", "FormatRangeandundo");

// undo the three previous actions.

Object Times = 3;

ThisDocument.undo (ref Times);

RNG.select ();

MessageBox.show ("Undo 3 Actions", "FormatRangeandundo");

// Apply the Normal Indent Style.

Object style = "normal indent";

RNG.SET_STYLE (REF Style);

RNG.select ();

Messagebox.show ("Normal Indent Style Applied",

"FormatRangeandundo");

// Undo a single action.

Times = 1;

ThisDocument.undo (ref Times);

RNG.select ();

MessageBox.show ("Undo 1 Action", "FormatRangeandundo");

}

Tip Because the

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 each 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

.

INSERTING TEXT

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 THEEN SETETED TEXT. Figure Figure 11 Shows The results after the code has run. 'Visual Basic

DIM STR AS STRING = "New TEXT"

DIM RNG As Word.Range = thisDocument.range (0, 0)

RNG.TEXT = STR

RNG.select ()

// c #

String str = "new text";

Object start = 0;

Object end = 0;

Word.Range RNG = thisDocument.range (Ref start, ref end);

RNG.TEXT = STR;

RNG.select ();

Figure 11. Inserting new text at an insertion point

Replacing Text in a Range

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.

'Visual Basic

RNG = thisDocument.range (0, 12)

RNG.TEXT = STR

RNG.select ()

// c #

START = 0;

End = 12;

RNG = thisDocument.range (ref start, ref end);

RNG.TEXT = STR;

RNG.select ();

Figure 12. Inserting New Text over existing text

Collapsing a Range Or Selection

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....................................

'Visual Basic

DIM STR AS STRING = "New TEXT"

DIM RNG As Word.Range = _

ThisDocument.Paragraphs (1). Range

RNG.COLLLAPSE (Word.WDCOLLLAPSEDIRECTION.WDCOLLLAPSSTART)

RNG.TEXT = STR

RNG.select ()

// c #

String str = "new text";

Word.Range RNG = thisdocument.Paragraphs [1] .range;

Object direction = word.wdcollapsedirection.wdcollapsestart;

RNG.COLLLAPSE (REF DIRECTION);

RNG.TEXT = STR;

RNG.select ();

Figure 13. The text you Insert After collapsing a paragraph range gets inserted at the beginning of the paragraph.

If you use the wdcollapsend value

'Visual Basic

Rng.collapse (word.wdcollapsedirection.wdcollapsend)

// c #

Object direction = word.wdcollapsedirection.wdcollapsend;

RNG.COLLLAPSE (REF DIRECTION);

Figure 14. Collapsing The end of a paragraph inserts text in the next 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.

Inserting Text and Dealing with Paragraph Marks

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:. 'Visual Basic

Friend Sub ManipulateraNGtext ()

'Retrieve Contents of First and Second Paragraphs

DIM str1 as string = thisdocument.paragraphs (1) .range.text

Dim str2 as string = thisdocument.Paragraphs (2) .range.text

// c #

Public void manipulaterangetext ()

{

// Retrieve Contents of First and Second Paragraphs

String str1 = thisdocument.paragraphs [1] .range.text;

String str2 = thisdocument.paragraphs [2] .range.text;

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.

'Visual Basic

'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, "ManipulateraNGtext")

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, "ManipulateraNGtext"); rng2.select ();

Messagebox.show (RNG2.Text, "ManipulaterAngeText");

Figure 15. The first and second paragraphs have been swapped, and rng1 is success.

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.:

'Visual Basic

RNG1.Movend (Word.wdunits.wdcharacter, -1)

'Write New Text for Paragraph 1.

RNG1.Text = "New Content for Paragraph 1."

// c #

Object unit = word.wdunits.wdcharacter;

Object count = -1;

RNG1.Movend (Ref Unit, ref count);

// Write New Text for Paragraph 1.

RNG1.Text = "New Content for Paragraph 1.";

The Following Section of Code Simply Replaces The Text In RNG2, Including The Paragraph Mark:

'Visual Basic

RNG2.Text = "New Content for Paragraph 2."

// c #

RNG2.Text = "New Content for Paragraph 2.";

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 Highlight; It has been merge INTO What WAS Formerly The Third Paragraph And no longer exists as a paragraph on its OWN.

'Visual Basic

'Pause to Display the results.

RNG1.SELECT ()

Messagebox.show (RNG1.Text, "ManipulateraNGtext")

RNG2.SELECT ()

Messagebox.show (RNG2.Text, "ManipulaterAngetext")

// c #

// pause to display the results.rng1.select ();

Messagebox.show (RNG1.Text, "ManipulateraNGtext");

RNG2.SELECT ();

Messagebox.show (RNG2.Text, "ManipulaterAngeText");

Figure 16. The New Content Insert In RNG2 Overwrote The Paragraph Mark.

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:

'Visual Basic

RNG1.Movend (Word.WDUnits.wdcharacter, 1)

// c #

Unit = word.wdunits.wdcharacter;

count = 1;

RNG1.Movend (Ref Unit, ref count);

THIS WILL RESTORE THIRD Paragraph To Its Original Position.

'Visual Basic

RNG2.DELETE ()

// c #

// Note That in C #, You Must Specify

// Both Parameters - It's up to you

// TO Calculate The Length of the Range.

Unit = word.wdunits.wdcharacter;

Count = rng2.characters.count;

RNG2.Delete (Ref unit, ref count);

The Code Then Restores The Original Paragraph Text In RNG1:

'Visual Basic

RNG1.TEXT = STR1

// c #

RNG1.Text = STR1;

.......................

Figure 17 Displays The Three Paragraphs, with RNG1 Selected. Note That The Second Paragraph Is Now include in RNG1, Which Has Been Extended to include THE INSERTED Text.

'Visual Basic

RNG1.INSERTAFTER (STR2)

RNG1.SELECT ()

End Sub

// c #

RNG1.INSERTAFTER (STR2);

RNG1.Select ();

}

Figure 17. The insertafter method to include the inserated text.the bookmark Object

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.

Creating a bookmark

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. 'Visual Basic

Friend Sub CreatebookMarks ()

DIM RNG As Word.Range

DIM Bookmk1 as Word.Bookmark

DIM Bookmk2 as Word.bookmark

'Display Bookmarks.

ThisDocument.activeWindow.view.showBookmarks = true

// c #

Public void createbookmarks ()

{

Word.range RNG;

Word.bookmark bookmk1;

Word.bookmark bookmk2;

// Display Bookmarks.

ThisDocument.activeWindow.view.showbookmarks = true;

Defines a Range Object As The First Insert Point At the Beginning of The Document 'Visual Basic

RNG = thisDocument.range (0, 0)

// c #

Object start = 0;

Object end = 0; RNG = thisDocument.range (Ref start, ref end);

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. 'Visual Basic

Bookmk1 = thisdocument.bookmarks.add (_ _

"BookMK1", Directcast (RNG, Word.Range))

'Display the Bookmark.

Messagebox.show ("Bookmk1 Text:" & Bookmk1.Range.text, _

"CREATEBOOKMARKS")

// c #

Object Range = RNG;

Bookmk1 = thisdocument.bookmarks.add ("Bookmk1", Ref Range;

// Display the Bookmark.

Messagebox.show ("Bookmk1 Text:" Bookmk1.Range.Text,

"CreateBookmarks");

Figure 18. A Bookmark defined as an insertion point is displayed as an I-bar. 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 incruded in the bookmark. 'Visual Basic

RNG.INSERTBEFORE ("** insertbefore bookmk1 **")

'Show Bookmark Code.

Messagebox.show ("Bookmk1 Text:" & Bookmk1.Range.text, _

"CREATEBOOKMARKS")

// c #

RNG.INSERTBEFORE ("** Insertbefore Bookmk1 **");

// show bookmark text.

Messagebox.show ("Bookmk1 Text:" Bookmk1.Range.Text,

"CreateBookmarks");

Figure 19. The inserted text is 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. 'Visual Basicrng.insertafter ("** insertafter bookmk1 **")

Messagebox.show ("Bookmk1 Text:" & Bookmk1.Range.text, _

"CREATEBOOKMARKS")

// c #

RNG.INSERTAFTER ("** insertafter bookmk1 **);

Messagebox.show ("Bookmk1 Text:" Bookmk1.Range.Text,

"CreateBookmarks");

Figure 20. Inserting text after the Bookmark. 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. 'Visual Basic

RNG = thisDocument.Paragraphs (2) .range

'Create New Bookmark on The Second Paragraph.

Bookmk2 = thisdocument.bookmarks.add (_

"BookMK2", Directcast (RNG, Word.Range))

Messagebox.show ("Bookmk2 Text:" & Bookmk2.Range.Text, _

"BookMK2 SET")

// c #

RNG = thisdocument.paragraphs [2] .range;

// Create New Bookmark On Paragraph 2.

Range = RNG;

Bookmk2 = thisDocument.bookmarks.add ("Bookmk2", Ref Range;

Messagebox.show ("Bookmk2 Text:" Bookmk2.Range.Text,

"Bookmk2 Set");

Figure 21. A Bookmark encompassing a range of text is displayed as open and closed square brackets. Uses InsertBefore to insert text before the Bookmark. Figure 22 shows that the inserted text is now included in the Bookmark. 'Visual Basic

RNG.INSERTBEFORE ("** INSERTBEFORE BOOKMK2 **") MessageBox.show ("Bookmk2 Text:" & Bookmk2.Range.Text, _

"INSERTBEFORE BOOKMK2")

// c #

RNG.INSERTBEFORE ("** Insertbefore Bookmk2 **");

Messagebox.show ("Bookmk2 Text:" Bookmk2.Range.Text,

"INSERTBEFORE BOOKMK2");

Figure 22. When the Bookmark is a range of text, the InsertBefore method adds it to 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. 'Visual Basic

'INSERT TEXT AFTER.

RNG.INSERTAFTER ("** INSERTAFTER BOOKMK2 **")

Messagebox.show ("Bookmk2 Text:" & Bookmk2.Range.Text, _

InsertAfter Bookmk2 ")

Bookmk2.select ()

Messagebox.show ("Bookmk2.select ()", "CreateBookmarks")

// c #

RNG.INSERTAFTER ("** insertafter bookmk2 **");

Messagebox.show ("Bookmk2 Text:" Bookmk2.Range.Text,

"INSERTAFTER BOOKMK2");

Bookmk2.select ();

Messagebox.show ("Bookmk2.select ()", "CreateBookMarks");

Figure 23. Text INSERTED AFTER A Bookmark Is Not Included in The Bookmark.

The Bookmarks Collection

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 itsheng.text property using the messagebox.show method:

'Visual Basic

Friend Sub ListbookMarks ()

DIM SW AS New StringWriterdim Bmrk As Word.Bookmark

For Each Bmrk in thisDocument.bookmarks

SW.WRITELINE ("Name: {0}, Contents: {1}", _

BMRK.NAME, BMRK.RANGE.TEXT)

NEXT

MessageBox.show (sw.toString (), "Boomarks and Contents")

End Sub

// c #

Public void ListbookMarks ()

{

StringWriter SW = new stringwriter ();

Foreach (Word.Bookmark Bmrk in thisDocument.bookmarks)

{

SW.writeLine ("name: {0}, contents: {1}",

BMRK.NAME, BMRK.RANGE.TEXT);

}

MessageBox.show (sw.toString (), "Bookmarks and Contents");

}

Updating the Bookmark Text Property

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.

'Visual Basic

Friend Sub BookmarkText ()

'Create a bookmark on the first paragraph.

With thisdocument

.Bookmarks.add ("bkmark", _

.Paragraphs (1) .range)

'Create Range on Bookmark Object.

DIM RNG As Word.Range = _

.Bookmarks ("bkmark"). Range

'Replace Range Text (this deletes the Bookmark).

RNG.Text = "New Bookmark Text."

'Re-create the bookmark.

.Bookmarks.add (_

"BKMARK", Directcast (RNG, Word.Range))

'Display Bookmark.

.ActiveWindow.view.showbookmarks = true

Messagebox.show (.bookmarks ("BKMARK"). Range.Text, _

"BookmarkReplacetext")

End with

End Sub

// c # public void bookmarkText ()

{

// Create a Bookmark on the first paragraph.

Object Range = thisDocument.Paragraphs [1] .range;

ThisDocument.bookmarks.add ("BKMARK", Ref Range;

// CREATE RANGE ON BOOKMARK OBJECT.

Object name = "bkmark";

Word.Range RNG = thisDocument.bookmarks.get_item (ref name) .range;

// Replace Range Text (this deletes the Bookmark).

RNG.TEXT = "New Bookmark Text."

// recreate the bookmark.

Range = RNG;

ThisDocument.bookmarks.add ("BKMARK", Ref Range;

// Display Bookmark.

ThisDocument.activeWindow.view.showbookmarks = true;

Name = "bkmark";

Messagebox.show (thisDocument.bookmarks.

Get_item (ref name) .Range.Text, "BookmarkReplacetext");

}

Figure 24. The Original Bookmark Is Replaced with new text.

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.:

'Visual Basic

Friend Sub ReplaceBookmarkText (_

Byval bookmarkname as string, _

Byval newText As String)

IF thisdocument.bookmarks.exists (BookmarkName) THEN

DIM RNG As Word.Range = _

ThisDocument.bookmarks (BookmarkName) .range. Range

RNG.Text = NewText

ThisDocument.bookmarks.add (_

BookmarkName, Directcast (RNG, Word.Range))

END IF

End Sub

// c #

Public void replacebookmarktext (String BookmarkName,

String newText)

{

IF (thisDocument.bookmarks.exists (bookmarkname))

{

Object name = bookmarkname;

Word.Range RNG = thisDocument.bookmarks.

GET_ITEM (Ref name) .range;

RNG.TEXT = NewText;

Object Range = RNG;

ThisDocument.bookmarks.add (BookmarkName, Ref Range);

}

}

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

'Visual Basic

ReplacBookmarkText ("FirstnameBookmark", "Joe")

// c #

ReplaceBookmarkText ("Firstnamebookmark", "Joe");

Searching and replacing 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.

.

Finding text with a selection Object

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.

'Visual Basic

Public Sub FindInselectrion ()

'Move Selection to Beginning Of Doc.

Thisapplication.selection.homekey (_

Word.wdunits.wdstory, Word.wdmovementType.wdmove)

DIM STRFIND AS STRING = "Dolor"

DIM fnd as word.find = thisapplication.selection.findfnd.clearformatting ()

fnd.text = Strfind

IF fnd.execute () THEN

Messagebox.show ("Text Found.")

Else

Messagebox.show ("Text Not Found.")

END IF

End Sub

// c #

Public void findibself ()

{

// Move Selection to Beginning Of Doc.

Object unit = word.wdunits.wdstory;

Object Extend = Word.wdmovementType.wdmove;

ThisApplication.selection.homekey (Ref unit, ref extend);

Word.find fnd = thisapplication.selection.find;

fnd.clearformatting ();

Object findtext = "dolor";

Object matchcase = type.missing;

Object matchWholeWord = type.missing;

Object matchWildcards = type.missing;

Object matchsoldslike = type.missing;

Object matchallWordForms = type.missing;

Object forward = type.missing;

Object wrap = type.missing;

Object Format = type.missing;

Object replacewith = type.missing;

Object replace = type.missing;

Object matchkashida = type.missing;

Object matchdiacritics = type.missing;

Object matchalefhamza = type.missing;

Object matchControl = type.missing;

IF (fnd.execute (ref findtext, ref matchcase, ref matchwholeword,

Ref mathwildcards, ref matchsoundslike, ref mathalwordforms,

Ref Forward, Ref Wrap, Ref Format, Ref Replacewith,

Ref report, ref matchkashida, ref matchdiacritics,

Ref matchalefhamza, ref matchcontrol)

{

MessageBox.show ("Text Found.", "FindInselection";

}

Else

{

MessageBox.show ("Text Not Found.", "FindInseLection");

}

}

Figure 25. Found text is Automatically Selected WHEN Searching with a selection object.

Tip Find criteria are cumulative, which means that criteria are added to previous search criteria. You should get in the habit of clearing formatting from previous searches by using theClearFormatting method prior to each search.

Setting Find Options

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 is not required for Visual Basic developers, but the following example shows Off a useful technique for c # developers:

'Visual Basic

Public Sub criteriaspecify ()

'Use Find Properties to Specify Search Criteria.

With thisapplication.selection.find

.Clearformatting ()

.Forward = TRUE

.Wrap = word.wdfindwrap.wdfindcontinue

.Text = "ipsum"

.Execute ()

End with

'Use Execute Method Arguments to Specify Search Criteria.

With thisapplication.selection.find

.Clearformatting ()

.Execute (FindText: = "Dolor", _

Forward: = true, wrap: = word.wdfindwrap.wdfindContinue)

End with

End Sub

// c #

Public void criteriaspecify ()

{

// Use Find Properties to Specify Search Criteria.

Word.find fnd = thisapplication.selection.find; fnd.clearformatting ();

fnd.forward = true;

fnd.wrap = word.wdfindwrap.wdfindcontinue;

fnd.text = "IPSUM";

ExecuteFind (fND);

// Use Execute Method Arguments to Specify Search Criteria.

Fnd = thisapplication.selection.find;

fnd.clearformatting ();

Object findtext = "dolor";

Object wrap = word.wdfindwrap.wdfindcontinue;

Object forward = true;

ExecuteFind (fnd, wrap, forward);

}

Private Boolean ExecuteFind (Word.Find Find)

{

Return ExecuteFind (Find, Type.Missing, Type.Missing);

}

Private Boolean ExecuteFind

Word.Find Find, Object Wrapfind, Object ForwardFind

{

// Simple Wrapper Around Find.execute:

Object FindText = Type.Missing;

Object matchcase = type.missing;

Object matchWholeWord = type.missing;

Object matchWildcards = type.missing;

Object matchsoldslike = type.missing;

Object matchallWordForms = type.missing;

Object forward = forwardfind;

Object wrap = wrapfind;

Object Format = type.missing;

Object replacewith = type.missing;

Object replace = type.missing;

Object matchkashida = type.missing;

Object matchdiacritics = type.missing;

Object matchalefhamza = type.missing;

Object matchControl = type.missing;

Return Find.execute (Ref FindText, Ref Matchcase,

Ref matchWholeWord, Ref matchwildcards, ref matchsoundslike,

Ref matchalwordforms, ref forward, reform, ref format,

Ref replacewith, ref replace, ref matkashida,

Ref matchdiacritics, ref matchalefhamza, ref matchcontrol;

}

Finding text with a range Object

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, .

'Visual Basic

Public Sub Findinrange ()

'Set the second paragraph as the search range.

DIM RNG As Word.Range = _

ThisDocument.Paragraphs (2). Range

DIM fnd as word.find = rng.find

'CLEAR EXISTING FORMATTING.

fnd.clearformatting ()

'Execute the Search

fnd.text = "faucibus"

IF fnd.execute () THEN

MessageBox.show ("Text Found.", "FindInrange")

Else

MessageBox.show ("Text Not Found.", "FindInrange")

END IF

'The Word Faucibus Will Be Displayed IF THE

'Search succeeds; Paragraph 2 Will Be Displayed

'ness the search fails.

RNG.select ()

End Sub

// c #

Public void findinrange ()

{

// set the second paragraph as the search range.

Word.Range RNG = thisdocument.Paragraphs [2] .range;

Word.Find fnd = rng.find; // clear existing formatting.

fnd.clearformatting ();

// Execute the Search.

fnd.text = "faucibus";

EXECUTEFIND (FND))

{

MessageBox.show ("Text Found.", "FindInrange");

}

Else

{

MessageBox.show ("Text Not Found.", "FindInrange");

}

// the Word Faucibus Will Be Displayed IF THE

// Search succeeds; Paragraph 2 Will Be Displayed

// if The search fails.

RNG.select ();

}

Figure 26. if The Range Method's Find succeeds, The Range Will Be Redined to Contain The Search Criteria.

Looping Through Found items

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 Previous.

'Visual Basic

Public Sub FindinLoopandFormat ()

DIM INTFOUND AS INTEGER

Dim rngdoc as word.range = thisdocument.range

DIM fnd as word.find = rngdoc.find

'Find All Instances of The Word "Lorem" and bold each.

fnd.clearformatting ()

fnd.forward = true

fnd.text = "lorem"

fnd.execute ()

Do while fnd.found

'Set the new font weight and color.

'Note That Each "Match" Resets

'The search management.

RNGDoc.font.color = word.wdcolor.wdcolorred

RNGDOC.FONT.BOLD = 600INTFOUND = 1

fnd.execute ()

Loop

Messagebox.show (_

String.Format ("Lorem Found {0} Times.", Intfound, _

"FindinLoopandFormat")

End Sub

// c #

Public void FindinLoopandFormat ()

{

INT INTFOUND = 0;

Object start = 0;

Object End = thisdocument.characters.count;

Word.Range rngdoc = thisdocument.range (Ref start, ref end);

Word.find fnd = rngdoc.find;

// Find All Instances of the Word "Lorem" and bold each.

fnd.clearformatting ();

fnd.forward = true;

fnd.text = "lorem";

ExecuteFind (fND);

While (fnd.found)

{

// set the new font weight and color.

// Note That Each "Match" Resets

// The search future to be the bound text. // 's SEARCHING RANGE TO

RNGDoc.font.color = word.wdcolor.wdcolorred;

RNGDoc.font.bold = 600;

INTFOUND ;

ExecuteFind (fND);

}

Messagebox.show

String.Format ("Lorem Found {0} Times.", Intfound,

"FindinLoopandFormat";

}

THE, RNGDOC, STARTED OUT REFERRING to the Entire Document's Contents, But Ends Up Referring to Each Match With Search. This is by design-when you call the

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.

Replacing text

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.:

'Visual Basic

Friend Sub Searchandreplace ()

With thisapplication.selection.find

.Clearformatting ()

.Text = "lorem"

With .replacement

.Clearformatting ()

.Text = "forum"

End with

.Execute (replace: = word.wdreplace.wdreplaceAll)

End with

End Sub

// c #

Public void searchReplace ()

{

// Move Selection to Beginning Of Document.

Object unit = word.wdunits.wdstory;

Object Extend = Word.wdmovementType.wdmove;

ThisApplication.selection.homekey (Ref unit, ref extend);

Word.find fnd = thisapplication.selection.find; fnd.clearformatting ();

fnd.text = "lorem";

fnd.replacement.clearformatting ();

fnd.replacement.text = "forum";

ExecuteReplace (fND);

}

Private Boolean ExecuteReplace (Word.Find Find)

{

Return EXECUTEREPLACE (Find, Word.wdReplace.wdreplaceAll);

}

Private Boolean ExecuteReplace (Word.Find Find,

Object replaceoption)

{

// Simple Wrapper Around Find.execute:

Object FindText = Type.Missing;

Object matchcase = type.missing;

Object matchWholeWord = type.missing;

Object matchWildcards = type.missing;

Object matchsoldslike = type.missing;

Object matchallWordForms = type.missing;

Object forward = type.missing;

Object wrap = type.missing;

Object Format = type.missing;

Object replacewith = type.missing;

Object replace = replaceoption;

Object matchkashida = type.missing;

Object matchdiacritics = type.missing;

Object matchalefhamza = type.missing;

Object matchControl = type.missing;

Return Find.execute (Ref FindText, Ref Matchcase,

Ref matchWholeWord, Ref matchwildcards, ref matchsoundslike,

Ref matchalwordforms, ref forward, reform, ref format,

Ref replacewith, ref replace, ref matkashida,

Ref matchdiacritics, ref matchalefhamza, ref matchcontrol;

}

Restoring The User's SelectionAfter A SEARCH

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:.. 'Visual Basic

Friend Sub ReplaceAndRestoreselection ()

'Save User's Original Selection.

Dim rngstart as word.range = _

Thisapplication.selection.range

'Define Search Range of Entire Document.

Dim rngsearch as word.range = thisdocument.range

With RNGSearch.Find

.Clearformatting ()

.Text = "vel"

With .replacement

.Clearformatting ()

.Text = "vello"

End with

.Execute (replace: = word.wdreplace.wdreplaceAll)

End with

'Restore User's Original Selection.

RNGStart.select ()

End Sub

// c #

Public void replaceandRestoreselection ()

{

// Save User's Original Selection.

Word.Range RNGStart = thisapplication.selection.range;

// Define search range of entire document.

Object start = 0;

Object End = thisdocument.characters.count;

Word.Range rngsearch = thisdocument.range (Ref start, ref end);

Word.find fnd = rngsearch.find;

fnd.clearformatting ();

fnd.text = "vel";

fnd.replacement.clearformatting ();

fnd.replacement.text = "vello";

ExecuteReplace (fND);

// Restore User's Original Selection.

RNGStart.select ();

}

Printing

Word Possesses a Rich Set of Built-in Functionality When It comes to printing. It's Very Easy To Work with the print engine to print out entire documents or seat of documents.working with print preview

You Can Display A Document In Print Preview Mode by Setting The Active Document's PrintPreview Property to True:

'Visual Basic

ThisDocument.printpreview = TRUE

// C #

ThisDocument.printpreview = 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:

'Visual Basic

Friend Sub TogglePrintpreview ()

Thisapplication.printpreview = not thisapplication.printpreview

End Sub

// C #

Public void togglePrintpreview ()

{

ThisApplication.printpreview =! ThisApplication.printpreview;

}

The PrintOut Method

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..:

'Visual Basic

ThisDocument.printOut ()

// C #

Object background = type.missing;

Object append = type.missing;

Object Range = type.missing;

Object outputfilename = type.missing;

Object from = Type.Missing;

Object to = Type.missing;

Object item = type.missing;

Object copies = type.missing;

Object pages = type.missing;

Object PageType = Type.Missing;

Object powder = type.missing;

Object collate = type.missing;

Object filename = type.missing;

Object activeprintermacgx = type.missing; Object ManualduplexPrint = type.missing;

Object printzoomcolumn = type.missing;

Object printzoomrow = type.missing;

Object printzoompaperWidth = type.missing;

Object printzoompaperHeight = type.missing;

ThisDocument.printout (Ref Background, REF APPEND,

Ref Range, Ref OutputFileName, Ref from, Ref to,

Ref Item, Ref Copies, Ref Pages, Ref PageType,

Ref printtofile, Ref collate, Ref ActivePrintermacgx,

Ref manualduplexprint, ref printzoomcolumn, ref printzoomrow,

Ref printzoompaperWidth, ref printzoompaperHeight;

The Printout Method Has Multiple Optional Arguments That Allow You To Fine Tune How To Print The Document, as Summarized in Table 2.

Table 2. Commonly Used Print Arguments

ArgumentDescriptionBackgroundSet to True to allow processing while Word prints the documentAppendUse 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.RangeThe page range. Can be any WdPrintOutRange enumeration: wdPrintAllDocument, wdPrintCurrentPage, wdPrintFromTo, wdPrintRangeOfPages, or wdPrintSelection OutputFileNameIf PrintToFile is True, this argument specifies the path and file name of the output file.FromThe starting page number when Range is set to wdPrintFromToToThe ending page number when Range is set to wdPrintFromToItemThe item to be printed Can be any WdPrintOutItem enumeration:.. wdPrintAutoTextEntries, wdPrintComments, wdPrintDocumentContent, wdPrintKeyAssignments, wdPrintProperties, wdPrintStylesCopiesThe number of copies to be printedPagesThe page numbers and page ranges to be printed, separated by commas For example, "2 , 6-10 "prints page 2 and pages 6 through 10.PageTypeThe type of pages to be printed Can be any WdPrintOutPages constant:.. WdPrintAllPages, wdPrintEvenPagesOnly, wdPrintOddPagesOnlyPrintToFileSet to True to send printer instructions to a file Make sure to specify a file name with OutputFileName.CollateUse when printing multiple copies of a document. Set to True to print all pages of the document before printing the next copy.FileNameAvailable 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.manualduplexprintset 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: 'Visual Basic

Friend Sub PrintOutdoc ()

ThisDocument.printout (_

Background: = True, _

Append: = false, _

Range: = word.wdprintoutrange.wdprintcurrentpage, _

Item: = word.wdprintoutItem.wdprintDocumentContent, _

COPIES: = 2, _

Pages: = 1, _

PageType: = word.wdprintoutpages.wdprintallpages, _

PRINTTOFILE: = FALSE, _

Collate: = True, _

ManualDuplexprint: = false)

End Sub

// c #

Public void printOutdoc ()

{

Object Background = true;

Object append = false;

Object Range = Word.wdprintOrge.wdprintCurrentPage;

Object outputfilename = type.missing;

Object from = Type.Missing;

Object to = Type.missing;

Object item = word.wdprintoutItem.wdprintDocumentContent

Object copies = 2;

Object Pages = 1;

Object PageType = word.wdprintoutpages.wdprintallpages;

Object printetoftile = false;

Object collate = type.missing;

Object filename = type.missing;

Object ActiveprinterMacgx = type.missing;

Object manualduplexprint = type.missing;

Object printzoomcolumn = type.missing;

Object printzoomrow = type.missing;

Object printzoompaperWidth = type.missing;

Object printzoompaperHeight = type.missing;

ThisDocument.printout (Ref Background, REF APPEND,

Ref Range, Ref OutputFileName, Ref from, Ref to,

Ref Item, Ref Copies, Ref Pages, Ref PageType,

Ref printtofile, Ref collate, Ref ActivePrintermacgx,

Ref manualduplexprint, ref printzoomcolumn, ref printzoomrow,

Ref printzoompaperWidth, ref printzoompaperHeight;

}

Creating Word Tables

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 Column At The Beginning of The Active Document: 'Visual Basic

DIM RNG As Word.Range = _

ThisDocument.range (0, 0)

ThisDocument.Tables.Add (RNG, 3, 4)

// c #

Object start = 0;

Object end = 0;

Word.Range RNG = thisDocument.range (Ref start, ref end);

Object defaulttablebehavior = type.missing;

Object automitbehavior = type.missing;

ThisDocument.tables.Add (RNG, 3, 4, Ref defaulttablebehavior,

Ref autofitbehavior;

Working with a Table Object

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 ITEM Number, as Shown In The Following Code Fragment:

'Visual Basic

DIM TBL As Word.table = thisdocument.tables (1)

// c #

Word.table tbl = thisdocument.tables [1];

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.:

'Visual Basic

With thisdocument.tables (1)

.Range.font.size = 8

.Style = "Table Grid 8"

End with

// c #

Word.table tbl = thisdocument.tables [1];

TBL.Range.Font.size = 8;

Object style = "Table Grid 8";

TBL.SET_STYLE (REF Style);

The Cells Collection

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: 'Visual Basic

With thisdocument.tables (1)

With .cell (1, 1) .RANGE

.Text = "name"

.Paragraphformat.Alignment = _

Word.wdparagraphagramhalignment.wdalignparagraphRight.wdalignparagraplay

End with

End with

// c #

Word.Range RNG = thisdocument.tables [1] .cell (1, 1) .range;

RNG.Text = "Name";

RNG.PARAGRAPHFORMAT.Alignment =

Word.wdparagraphalignment.wdalignparagraphright;

Rows and columns

The Cells in a Table Area Organized Into Rows and Columns. You Can Add A New Row to a Table by Using The Add Method:

'Visual Basic

DIM TBL As Word.table = thisdocument.tables (1)

TBL.ROWS.ADD ()

// c #

Word.table tbl = thisdocument.tables [1];

Object beforerow = type.missing;

Tbl.Rows.Add (Ref Beforelow);

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:

'Visual Basic

DIM TBL As Word.table = thisdocument.tables (1)

TBL.COLUMNS.ADD (TBL.COLUMNS (1))

TBL.COLUMNS.DISTRIBUTEWIDTH

// c #

Word.table tbl = thisdocument.tables [1];

Object BeforeColumn = TBL.COLUMNS [1];

TBL.COLUMNS.ADD (REF BeforeColumn);

Tbl.columns.distributeWidth ();

Pulling it all together

The Following Example Creates A Word Table At The End of The Active Document and Populates It With Document Properties: 'Visual Basic

Public Sub CreateTable ()

'Move to Start of Document.

DIM RNG As Word.Range = _

ThisDocument.range (0, 0)

'INSERT SOME TEXT AND Paragraph Marks.

RNG.INSERTBEFORE ("Document Statistics")

RNG.Font.Name = "verdana"

Rng.font.size = 16

RNG.Insertparagraphafter ()

RNG.Insertparagraphafter ()

RNG.SetRange (rng.end, rng.end)

'Add the table.

DIM TBL AS WORD.TABLE = RNG.TABLES.ADD (_

ThisDocument.Paragraphs (2). Range, 3, 2)

'Format the Table and Apply A Style.

TBL.Range.Font.size = 12

TBL.COLUMns.DistributeWidth ()

TBL.Style = "Table Colorful 2"

'INSERT TEXT IN CELLS.

Tbl.cell (1, 1) .range.text = "Document Property"

Tbl.cell (1, 2) .range.text = "Value"

Tbl.cell (2, 1) .range.text = "Number of Words"

Tbl.cell (2, 2) .range.text = thisdocument.Words.count.toString

Tbl.cell (3, 1) .range.text = "Number of Characters"

Tbl.cell (3, 2). over.text = _

Thisdocument.characters.count.toString

Tbl.select ()

End Sub

// c #

Public void createtable ()

{

//Move to start of document.

Object start = 0;

Object end = 0;

Word.Range RNG = thisDocument.range (Ref start, ref end);

// INSERT SOME TEXT AND Paragraph Marks.

RNG.INSERTBEFORE ("Document Statistics");

RNG.FONT.NAME = "verdana";

RNG.FONT.SIZE = 16;

RNG.INSERTPARAGRAFTER ();

RNG.INSERTPARAGRAFTER ();

RNG.SetRange (rng.end, rng.end);

// add the table.

Object defaulttablebehavior = type.missing;

Object automitbehavior = type.missing;

Word.Table TBL = RNG.Tables.Add (thisDocument.Paragraphs [2] .range, 3, 2,

Ref defaulttablebehavior, ref autofitbehavior;

// Format The Table and Apply A Style.

TBL.Range.Font.size = 12;

Tbl.columns.distributeWidth ();

Object style = "Table Colorful 2";

TBL.SET_STYLE (REF Style);

// INSERT TEXT IN CELLS.

Tbl.cell (1, 1) .range.text = "Document Property";

Tbl.cell (1, 2) .range.text = "value";

Tbl.cell (2, 1) .range.text = "Number of Words";

Tbl.cell (2, 2). over.text =

ThisDocument.Words.count.toString ();

Tbl.cell (3, 1) .range.text = "Number of Characters";

Tbl.cell (3, 2). over.text =

ThisDocument.characters.count.toString ();

Tbl.select ();

}

Summary

Word has a rich object model that enables you to programmatically control Word and the creation of documents from managed code. This article has only scratched the surface of what's available. Should you wish to investigate further, see the online Help file for VBA in Word. Armed with the information from this article you shop becoming..............

转载请注明原文地址:https://www.9cbs.com/read-100058.html

New Post(0)