Understanding the Word Object Model from a Visual Studio 2005 Developer's Perspective

 

Ken Getz
MCW Technologies, LLC

December 2005

Applies to:
    Microsoft Visual Studio 2005 Tools for the Microsoft Office System
    Microsoft Office Word 2003

Summary: Learn how you can use objects provided by Microsoft Office Word 2003 to create managed code solutions with Microsoft Visual Studio 2005 Tools for the Microsoft Office System. Code examples demonstrate how to work with Word 2003 applications and documents, and with important properties and methods. (90 printed pages)

Note   In the MSDN Library, you can read Understanding the Word Object Model from a .NET Developer's Perspective as it applies to Microsoft Visual Studio Tools for the Microsoft Office System, Version 2003, Microsoft Office Word 2003, and Microsoft Visual Studio .NET 2003.

Download OfficeVSTOWordOM.msi.

Contents

Introduction
Getting Started with a Word Project
The Underpinnings: Documents and Templates
Bird's-Eye View of the Word Object Model
The Application Object
The Document Object
The Selection Object
The Range Object
The Bookmark Object
Searching and Replacing Text
Printing
Creating Word Tables
Conclusion
Additional Resources
About the Author

Introduction

Microsoft Office Word 2003 is 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 2005 Tools for the Microsoft Office System enables developers to interact with the objects provided by the Word object model by using a .NET language, such as Visual Basic or C#. Word possesses a rich set of features, all of which are accessible through code. There are quite a few objects to learn about, which can be confusing when you are 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, the Application and Document classes. Focus on these two classes is logical when you consider that most of the time you work with the Word application itself, or manipulate Word documents in some way.

As you work with the Word 2003 object model, you 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 find that everything you can do in the Word UI you can 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 learn how to take advantage of many of the objects in Word 2003, and you are introduced to some of the properties, methods, and events of each object. You learn how to work with Word applications and documents, as well as with some of their more important methods and properties.

**Note   **Programming Word and its objects from Microsoft Visual Basic 2005 feels much like programming in Microsoft Visual Basic for Applications (VBA). Visual Basic 2005 handles optional parameters, and allows late binding, just like VBA. On the other hand, C# provides unique challenges when programming against the Word object model. Because C# does not support optional parameters, parameterized properties, or late binding, you must handle many of the Word methods and properties specially when programming in C#. This document points out the differences between Visual Basic 2005 and C# programming, as they come up.

Getting Started with a Word Project

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

You can create either a Word Document or a Word Template project in Visual Studio 2005

Figure 1. You can create either a Word Document or a Word Template project in Visual Studio 2005

To make things easier for developers using Visual Studio 2005 Tools for Office, the Word project templates provide easy access to the Word Application object, and to the current document. Developers can use the Application reference to work with the Application object. In addition, the Globals class provides references to the document, using the Globals.ThisDocument property.

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 cover all of the members here: You get enough of the flavor of the object model to be able to get started, and you learn enough to use the Word Help for more details.

**Tip   **Throughout this article, you see many uses of the CType operator in the Visual Basic code. The reason for this is that the sample project has its Option Strict setting on. This means that Visual Basic requires strict type conversions. Many Word methods and properties return Object types: Therefore, to be as rigorous about conversions as possible, the sample has enabled Option Strict, and handles each type conversion explicitly. If you are a C# developer, you likely appreciate this decision. However, as you 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 with Option Strict off. For the most part, you want to work with Option Strict on; you learn about the few exceptions as they arise.

The Underpinnings: Documents and Templates

Before you can effectively program Word, you need to understand how Word works. Most of the actions you perform in code have equivalents in the user interface on the menus and toolbars. There is also an underlying architecture 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&#151a; 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&#151Word; documents have a .doc 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 are 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 want.

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 document's code behind project.

Procedure references are fully qualified when you assign them to a toolbar

Figure 2. Procedure references are fully qualified when you assign them 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&#151Normal;.dot, a custom template, and the current document&#151the; one in the document is used first, then the one in the custom template, and then 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.

The default paragraph style is Normal

Figure 3. The default paragraph style is Normal

Modifying Styles

When you click 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 are saved in the document, and do not propagate back to the template the document was based on.

Modifying a style

Figure 4. Modifying a style

When working with Word, you 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 is important to understand how they work so that you can take advantage of them to make your code more efficient.

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 are meant to be read, such as the letters and numbers, and others are not, such as spaces, tabs and carriage returns. Each of these characters has a task to perform.

In addition to separating one paragraph from another, a paragraph mark plays a very important role in a Word document: it contains all of the information about how the paragraph is formatted. When you copy a paragraph and include the paragraph mark, all of the formatting in the paragraph travels along with it. If you copy a paragraph and omit the paragraph mark, the formatting of the original paragraph is 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.

The line break does not take paragraph formatting with it and a paragraph mark does

Figure 5. The line break does not take paragraph formatting with it and a paragraph mark does

Displaying Paragraph Marks

If you inadvertently delete a paragraph mark, it is possible you will 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.

Displaying Paragraph marks in the Formatting marks section of the Options dialog box

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

The Application object contains the Document, Selection, Bookmark, and Range objects

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 formatting 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. It is defined by a starting character position and an ending character position. You are not limited to a single Range object; you can define multiple Range objects in the same document. A Range object has the following characteristics:

  • It can consist of only an insertion point, a range of text, or the entire document.
  • It includes non-printing characters such as spaces, tab characters, and paragraph marks.
  • It can be the area represented by the current selection, or it can represent a different area than the current selection.
  • It is dynamic; it exists only so long as the code that creates it is running.

When you insert text at the end of a range, Word automatically expands the range to include the inserted text.

The Bookmark Object

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 object 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.
  • It 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.)

To make it easier for you to work with bookmarks in a Word document or template, Visual Studio 2005 Tools for Office adds a new Bookmark host control. This control provides features that make working with bookmarks much like working with any managed control. You can set and retrieve properties, call methods, and react to events. For more information about the Bookmark host control, see the Word Bookmark object in the Microsoft Office Word 2003 Visual Basic for Applications Language Reference.

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 a Bookmark object, you can use the Bookmark object's Range property to create a Range object, and then use one of the Range object's methods to modify the text.
  • You can define boilerplate text in a document by using a Bookmark object. You specify its contents using a Range or a Selection object as the source. You can then conditionally navigate to various Bookmarks at some future time to copy and paste the boilerplate text into other documents.

These are just a few of the ways in which you can make use of these objects to build powerful customized applications.

The 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 the Application Reference

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 are creating Visual Studio 2005 solutions, you can use the Application variable defined for you within your project.

If you are automating Word from outside this class, you must create a Word Application object variable and then create 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 Visual Studio 2005 Tools for Office project the same way that the built-in Application reference does. However, it is an unnecessary extra step to create a Word.Application variable explicitly because Application is already created for you. If you are automating Word without the benefit of Visual Studio 2005 Tools for Office, you need to create a new reference, as shown in the previous code sample.

When you are referring to objects and collections beneath the Application object, you do not need to refer to the Application object explicitly. For example, you can refer to the document associated with the code-behind assembly without the Application object by using the built-in Globals.ThisDocument property; additionally you can use Me in Visual Basic (or this in C#) when you are working in the ThisDocument code module. Globals.ThisDocument allows you to work with members of the Document object. The Document object is covered more fully in later sections of this document.

**Tip   **The Application.ActiveDocument property, which refers to the active Document object, retrieves a reference to the current Word document. You generally want to use Globals.ThisDocument instead of Application.ActiveDocument syntax, however. Using the Globals.ThisDocument reference provides you with extra features provided by Visual Studio 2005 Tools for Office, such as the ActionsPane object.

Application Properties

After you add a reference to an Application object, you can work with its methods and properties. The Application object provides a large set of methods and properties that you can use in your code to control Word. Most of the members of the Application object apply to global settings or the environment rather than to the contents of individual documents. Setting or retrieving some properties often requires only a single line of code; other retrievals are more complex.

  • ActiveWindow: Returns a Window object that represents the window that has the focus. This property allows you to work with whatever window has the focus. The sample code below creates a new window based on the current document and then uses the Arrange method of a Window object to tile the two windows. Note that the Arrange method uses the WdArrangeStyle.wdTiled enumerated value. (The sample application does not create a new window based on the current document: it instead creates a new document. Because the sample uses an actions pane to provide its demonstration menu, you cannot create a new window based on the current document. That feature is unavailable when using an actions pane. Therefore, the sample simply creates a new document to demonstrate the tiling feature.)

    [Visual Basic]
    Friend Sub CreateNewWindowAndTile()
        ' Create a new window from the active document.
        Dim wnd As Word.Window = _
          Application.ActiveWindow.NewWindow
        ' Tile the two windows.
        Application.Windows.Arrange( _
          Word.WdArrangeStyle.wdTiled)
    End Sub
    
    [C#]
    public void CreateNewWindowAndTile() 
    {
        // Create a new window from the active document.
        Word.Window wnd =  Application.ActiveWindow.NewWindow();
    
        // Tile the two windows.
        Object value = Word.WdArrangeStyle.wdTiled;
        Application.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 need to create an Object variable, assign the variable the value you want to pass to the method, and pass the variable using the ref keyword. You 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.
        Application.Caption = "My New Caption"
    End Sub
    
    [C#]
    public void SetApplicationCaption() 
    {
        // Change caption in title bar.
        Application.Caption = "My New Caption";
    }
    
  • CapsLock: Determines whether CapsLock is turned on, returning a Boolean value. The following procedure displays the state of CapsLock:

    [Visual Basic]
    Friend Sub CapsLockOn()
        MessageBox.Show("CapsLock is " & _
          Application.CapsLock.ToString())
    End Sub
    
    [C#]
    public void CapsLockOn() 
    {
        MessageBox.Show(Application.CapsLock.ToString());
    }
    
  • 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 are done, you want to ensure that DisplayAlerts gets set back to wdAlertsAll (generally, you reset this in a Finally block):

    [Visual Basic]
    Friend Sub DisplayAlerts()
        Try
            ' Turn off display of messages and alerts.
            Application.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone
            ' Your code runs here without any alerts.
            ' . . .code doing something here.
        Finally
            ' Turn alerts on again when done.
            Application.DisplayAlerts = Word.WdAlertLevel.wdAlertsAll
        End Try
    End Sub
    
    [C#]
    public void DisplayAlerts() 
    {
        // Turn off display of messages and alerts.
        try 
        {
            Application.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;
            // Your code runs here without any alerts.
            // . . .code doing something here.
    
        } 
        finally 
        {
            // Turn alerts on again when done.
            Application.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 switches the display of the status bar:

    [Visual Basic]
    Friend Sub ToggleStatusBar()
        Dim display As Boolean = Application.DisplayStatusBar
        Application.DisplayStatusBar = Not display
    End Sub
    
    [C#]
    public void ToggleStatusBar() 
    {
        // Toggle display of the status bar.
        bool display = Application.DisplayStatusBar;
        Application.DisplayStatusBar = !display;
    }
    
  • 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
            Application.System.Cursor = 
                Word.WdCursorType.wdCursorWait
            With Application.FileSearch
                .FileName = "*.doc"
                .LookIn = "C:\"
                .SearchSubFolders = True
                .Execute()
                For Each str In .FoundFiles
                    sw.WriteLine(str)
                Next
            End With
            MessageBox.Show(sw.ToString())
        Finally
            Application.System.Cursor = 
                Word.WdCursorType.wdCursorNormal
        End Try
    End Sub
    
    [C#]
    public void ListAllDocFilesOnC() 
    {
        try
        {
            Application.System.Cursor = Word.WdCursorType.wdCursorWait;
            StringWriter  sw = new StringWriter();
            Office.FileSearch fs = Application.FileSearch;
            fs.FileName = "*.doc";
            fs.LookIn = "C:\\";
            fs.SearchSubFolders = true;
            // Select the defaults, optional in VBA:
            fs.Execute(Office.MsoSortBy.msoSortByFileName, 
                Office.MsoSortOrder.msoSortOrderAscending, true);
            foreach (String str in fs.FoundFiles)
            {
                sw.WriteLine(str);
            } 
            MessageBox.Show(sw.ToString());
        }
        finally
        {
            Application.System.Cursor =   
              Word.WdCursorType.wdCursorNormal;
          }
    }
    

    **Tip   **In this example, note that Visual Basic developers do not need to pass all the parameters to the Execute method, as they are all optional. However, C# developers must pass every parameter. In this case, the code supplies values that match the default values. For reference-type parameters, you can pass a variable containing the System.Type.Missing value, indicating to Word that it should treat the parameters as if you had not passed a value at all. (So that you can avoid having to create a variable containing System.Type.Missing each time you need to use it, the Visual Studio 2005 Tools for Office template creates a variable named missing, which contains the value System.Type.Missing.) For value-type parameters, you must specify a value. You can use the VBA Help file in Word to determine the default values for the value-type parameters.

  • Path: When used with the Application object, returns the path of the current application:

    [Visual Basic]
    MessageBox.Show(Application.Path)
    
    [C#]
    MessageBox.Show(Application.Path);
    

    **Tip   **To return the path of the document, use Globals.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 are automatically updated, and hidden text and field codes are printed.

    [Visual Basic]
    ' Set various application options
    With Application.Options
        .BackgroundSave = True
        .Overtype = True
        .UpdateFieldsAtPrint = True
        .PrintHiddenText = True
        .PrintFieldCodes = True
    End With
    
    [C#]
    // Set various application options.
    Word.Options options = Application.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 then restores the original UserName.

    [Visual Basic]
    Friend Sub ChangeUserName()
        Dim str As String = Application.UserName
        MessageBox.Show(str)
        ' Change UserName.
        Application.UserName = "Dudley"
        MessageBox.Show(Application.UserName)
        ' Restore original UserName.
        Application.UserName = str
    End Sub
    
    [C#]
    public void ChangeUserName() 
    {
        string  str = Application.UserName;
        MessageBox.Show(str);
    
        // Change UserName.
        Application.UserName = "Dudley";
        MessageBox.Show(Application.UserName);
        // Restore original UserName.
        Application.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 are 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
        Application.Visible = False
        ' Do work here, invisibly.
    
    Catch ex As Exception
        ' Your exception handler here.
    
    Finally
        Application.Visible = True
    End Try
    
    [C#]
    try 
    {
        Application.Visible = false;
        // Do work here, invisibly.
    } 
    catch (Exception ex)
    {
        // Your exception handler here.
    } 
    finally 
    {
        Application.Visible = true;
    }
    

Application Methods

There are several useful methods of the Application object for performing actions involving Word. 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 useful if you just want to check the spelling of some text to obtain a yes/no answer to the question "Are there any spelling errors?" It does not display the errors or allow you to correct them. The following code checks the string "Speling erors here" 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 Application.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 erors here.";
    
        // The CheckSpelling method takes a bunch of optional parameters, in VBA:
        if (Application.CheckSpelling(str, ref missing,
          ref missing, ref missing, ref missing,
          ref missing, ref missing, ref missing,
          ref missing, ref missing, ref missing,
          ref missing, ref missing))
        {
            MessageBox.Show(String.Format("No errors in \"{0}\"", str));
        }
        else
        {
            MessageBox.Show(
             String.Format("\"{0}\" is spelled incorrectly", str));
        }
    }
    

    **Tip   **This example demonstrates another way in which Visual Basic developers have it easier than those developing in C#. The CheckSpelling method accepts a single required string parameter, followed by a number of optional parameters. C# developers must pass a series of values by reference—in this case, a number of instances of the System.Type.Missing variable, defined as simply missing within the Visual Studio 2005 Tools for Office project, for this very purpose. You might 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. If you are automating Word without using Visual Studio 2005 Tools for Office, you can easily emulate this behavior by creating a System.Object variable named missing, and assigning it the value System.Type.Missing.

  • 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 displays the Help About Microsoft Word dialog box:

    [Visual Basic]
    Friend Sub DisplayHelpAbout()
        Application.Help(Word.WdHelpType.wdHelpAbout)
    End Sub
    
    [C#]
    public void DisplayHelpAbout() 
    {
        Object value = Word.WdHelpType.wdHelpAbout;
        Application.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.
        Application.ActiveWindow.WindowState = _
          Word.WdWindowState.wdWindowStateNormal
    
        ' Position at upper left corner.
        Application.Move(0, 0)
    
        ' Size to 300 x 600 points.
        Application.Resize(300, 600)
    End Sub
    
    [C#]
    public void MoveAndResizeWindow() 
    {
        // None of this will work if the window is 
        // maximized or minimized.
        Application.ActiveWindow.WindowState = 
            Word.WdWindowState.wdWindowStateNormal;
    
        // Position at upper left corner.
        Application.Move(0, 0);
    
        // Size to 300 x 600 points.
        Application.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.
    Application.Quit(Word.WdSaveOptions.wdSaveChanges)
    
    ' Prompt to save changes.
    Application.Quit(Word.WdSaveOptions.wdPromptToSaveChanges)
    
    ' Quit without saving changes.
    Application.Quit(Word.WdSaveOptions.wdDoNotSaveChanges)
    
    [C#]
    // Automatically save changes.
    Object saveChanges = Word.WdSaveOptions.wdSaveChanges;
    Application.Quit(ref saveChanges, 
        ref missing, ref missing);
    
    // Prompt to save changes.
    saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;
    Application.Quit(ref saveChanges, 
        ref missing, ref missing);
    
    // Quit without saving changes.
    saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
    Application.Quit(ref saveChanges, 
        ref missing, ref missing);
    
  • SendFax: Launches the Fax Wizard, as shown in Figure 8. The user can then step through the Wizard to complete the operation.

    [Visual Basic]
    Friend Sub LaunchFaxWizard()
        Application.SendFax()
    End Sub
    
    [C#]
    public void LaunchFaxWizard() 
    {
        Application.SendFax();
    }
    

    The Fax Wizard can be launched by the SendFax method

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

[C#]
Word.Dialog dlg;

To specify the Word dialog box you are interested in, assign the variable to one of the values returned from the array of available dialog boxes:

[Visual Basic]
dlg = Application.Dialogs(Word.WdWordDialog.wdDialogFileNew)

[C#]
Dlg = Application.Dialogs[Word.WdWordDialog.wdDialogFileNew];

Once you create 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 Word.Dialog
    dlg = Application.Dialogs( _
      Word.WdWordDialog.wdDialogFileNew)
    dlg.Show()
End Sub

[C#]
public void DisplayFileNewDialog() 
{
    Word.Dialog dlg;
    dlg = Application.Dialogs[Word.WdWordDialog.wdDialogFileNew];
  dlg.Show(ref missing);
}

**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, you can ignore the parameter. In C#, pass System.Type.Missing by reference to indicate the default value, no time out at all.

Another good use for the Word dialogs is to do a spelling check on a document. The following procedure launches the spell checker for the document with the wdDialogToolsSpellingAndGrammar enumeration:

[Visual Basic]
Friend Sub DisplaySpellCheckDialog()
    Dim dlg As Word.Dialog
    dlg = Application.Dialogs( _
      Word.WdWordDialog.wdDialogToolsSpellingAndGrammar)
  dlg.Show()
End Sub

[C#]
public void DisplaySpellCheckDialog() 
{
    Word.Dialog dlg;
    dlg = Application.Dialogs
        [Word.WdWordDialog.wdDialogToolsSpellingAndGrammar];
    dlg.Show(ref missing);
}

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 time out value. The code in the following procedure uses the Display method, supplying an optional Timeout value that displays the UserInfo dialog box for approximately three seconds. If the user does not dismiss the dialog, it automatically closes:

    [Visual Basic]
    Friend Sub DisplayUserInfoDialog()
        Dim dlg As Word.Dialog
        dlg = Application.Dialogs( _
          Word.WdWordDialog.wdDialogToolsOptionsUserInfo)
        dlg.Display(3000)
    End Sub
    
    [C#]
    public void DisplayUserInfoDialog() 
    {
        Word.Dialog dlg;
        Object timeout = 3000;
        dlg = Application.Dialogs[
            Word.WdWordDialog.wdDialogToolsOptionsUserInfo];
        dlg.Display(ref timeout);
    }
    

**Tip   **Although it is 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 users click OK, they expect their changes to be saved, and if they click the Cancel button, they expect any edits to be abandoned.

[Visual Basic]
Dim returnValue As Integer = dlg.Display()

[C#]
int returnValue = dlg.Display(ref missing);

The possible return values are displayed in Table 1:

Table 1. Command button return values

Value Button clicked
-2 Close
-1 OK
0 (zero) Cancel
>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 are thrown away. You need to use the Execute method to apply changes within the dialog box explicitly.

  • Execute: If you simply call the Display method and then the user changes values in the dialog box, those changes are not applied. You need to use the Execute method after the Display method to apply any changes the user made explicitly. Unlike the Save method that saves user changes, all changes are 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 OK (returning a value of -1), the code uses the Execute method to apply the changes:

    [Visual Basic]
    Friend Sub DisplayExecuteDialog()
        Dim dlg As Word.Dialog
        dlg = Application.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 = Application.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 Application.UserName property.

  • Update: Use the Update method when you want to ensure that the dialog box is displaying the correct values. Because you can modify the contents of the dialog box using code, even after you retrieve 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&151;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 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 want to write code like the following to access these properties:

[Visual Basic]
Dim dlg As Word.Dialog
dlg = Application.Dialogs( _
  Word.WdWordDialog.wdDialogFilePageSetup)
dlg.PageWidth = 3.3
dlg.PageHeight = 6.6

Unfortunately, this code simply does not compile in Visual Basic with Option Strict set On or at all in C#. The PageWidth and PageHeight properties are not defined for the Dialog object until run time.

You have two options for working with these properties: you can create a Visual Basic file that includes the Option Strict Off setting at the top and place your code in that file, or you can find a way to perform late binding. Both C# and Visual Basic developers can take advantage of the System.Reflection namespace, which allows running code to determine available members of a specified type and performing a type of late binding. Given the member information, your code can use the System.Reflection namespace to invoke the property set procedure, for example, to set a property value.

In order to handle late-bound objects from within Visual Basic or C#, you can add a simple wrapper around the System.Reflection namespace's ability to set a property of an object whose capabilities are not known until run time:

[Visual Basic]
Private Sub InvokeHelper(ByVal dlg As Word.Dialog, _
 ByVal member As String, ByVal dlgValue As Object)
  Dim dlgType As Type = GetType(Word.Dialog)
    dlgType.InvokeMember(member, _
     BindingFlags.SetProperty Or _
     BindingFlags.Public Or BindingFlags.Instance, _
     Nothing, dlg, New Object() {dlgValue})
End Sub
[C#]
private void invokeHelper(Word.Dialog dlg, string member, Object dlgValue) 
{ 
  // Assumes a using statement in the file:
  // using System.Reflection;
  Type dlgType = typeof(Word.Dialog); 
  dlgType.InvokeMember(member, 
    BindingFlags.SetProperty | 
    BindingFlags.Public | 
    BindingFlags.Instance, 
    null, dlg, new object[] {dlgValue.ToString()}); 
}

In order to take advantage of the InvokeHelper method, pass in the Dialog object, the property to be set, and the value for the property, like this:

[Visual Basic]
Public Sub HiddenPageSetupDialog()
    Dim dlg As Word.Dialog
    dlg = ThisApplication.Dialogs( _
        Word.WdWordDialog.wdDialogFilePageSetup)

    InvokeHelper(dlg, "PageWidth", 3.3)
    InvokeHelper(dlg, "PageHeight", 6)
    dlg.Execute()
End Sub
[C#]
public void HiddenPageSetupDialog()
{
    Word.Dialog dlg;
    dlg = ThisApplication.Dialogs[
        Word.WdWordDialog.wdDialogFilePageSetup];
    invokeHelper(dlg, "PageWidth", 3.3);
    invokeHelper(dlg, "PageHeight", 6);
    dlg.Execute();
}

When deciding whether 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 are 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 use of the Word Dialog object, you need to look deeper than the included Word Help file. This file barely touches on the huge set of dialog boxes provided by Word. For more information, see Word 95 WordBasic Help File.

The Document Object

The bulk of your programming activity in Word will involve the Document object or its contents. In your Visual Studio 2005 Tools for Office project, you can always refer to the document that includes your customization code using the Globals.ThisDocument reference. All Word Document objects are also members of the Application object's Documents collection, which consists of all open documents. Using the Document object allows you to work with a single document, and the Documents collection allows you to work with all open documents. The Application and Document classes share many members as it is possible to perform document operations at both the Application and Document levels.

Some common tasks you can perform involving documents include:

  • Creating and opening documents
  • Adding, searching, and replacing text
  • Printing

Document Object Collections

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 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 fragment sets an object variable to refer to the first Document object in the Documents collection:

[Visual Basic]
Dim doc As Word.Document = _
  CType(Application.Documents(1), Word.Document)

[C#]
Word.Document doc = (Word.Document) Application.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 = _
  CType(Application.Documents("MyDoc.doc"), Word.Document)

[C#]
Word.Document doc = 
    (Word.Document) Application.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 2005 Tools for Office project, so your code is more efficient if you use the Globals.ThisDocument reference when you need to refer to the document that references the code-behind assembly. The following code fragment retrieves the name of the document:

[Visual Basic]
Dim str As String = Globals.ThisDocument.Name

[C#]
String str = Globals.ThisDocument.Name;

Opening, Closing, and Creating New Documents

The reference to the Globals.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 document. The first step in working with the Document object is to open an existing Word document or to create a new one.

Creating 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.
Application.Documents.Add()

[C#]
// Create a new document based on Normal.dot.
Application.Documents.Add( 
  ref missing, ref missing, ref missing, ref missing);

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

The Add method has an optional Template argument to create a new document based on a template other than Normal.dot. You need to supply the fully qualified path and file name where the template can be found.

[Visual Basic]
' Create a new document based on a custom template.
Application.Documents.Add( _
 "C:\Test\MyTemplate.Dot")

[C#]
// Create a new document based on a custom template.
Object template = @"C:\Test\MyTemplate.Dot";

Application.Documents.Add( 
    ref template, ref missing, ref missing, ref missing);

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 are created using the specified template. Coding your own new file routine might be easier in the end for your users, who might be confused when 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 FileName parameter:

[Visual Basic]
Application.Documents.Open("C:\Test\MyNewDocument")

[C#]
Object filename = @"C:\Test\MyNewDocument";
Application.Documents.Open(ref filename, ref missing,
  ref missing, ref missing, ref missing,
  ref missing, ref missing, ref missing,
  ref missing, ref missing, ref missing, ref missing,
  ref missing, ref missing, ref missing,
  ref missing);

Saving Documents

There are several ways to save and close documents, depending on what you want the 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 is prompted to save all files.

    [Visual Basic]
    Application.Documents.Save()
    
    [C#]
    Application.Documents.Save(ref missing, ref missing);
    
  • The following code sets the NoPrompt parameter to True, and saves all open documents without user intervention.

    [Visual Basic]
    Application.Documents.Save(NoPrompt:=True)
    
    [C#]
    Object noPrompt = true;
    Application.Documents.Save(ref noPrompt, ref missing);
    

    **Tip   **The default value for NoPrompt is False, so if you call Save without specifying a NoPrompt value in Visual Basic, or by specifying Type.Missing in C#, the user is prompted to save.

  • Save a Single Document: The Save method saves changes to a specified Document object. The following code fragment shows two ways to save a document:

    [Visual Basic]
    ' Save the document.
    Me.Save()
    
    ' or
    Application.ActiveDocument.Save()
    
    [C#]
    // Save the document.
    this.Save();
    // or
    Application.ActiveDocument.Save();
    
  • If you are not sure if the document you want to save is the active document, you can refer to it by its name. This code uses the Save method on a named document.

    [Visual Basic]
    Application.Documents("MyNewDocument.doc").Save()
    
    [C#]
    Object file = "MyNewDocument.doc";
    Application.Documents.get_Item(ref file).Save();
    

    **Tip   **Although Visual Basic 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 the hidden get_Item method, passing an index or name by reference, as in the previous example. C# developers can directly access elements of arrays (as in the Dialogs array shown previously), but for collections, you need to use the 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 cannot 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 Basic]
    Application.Documents(1).Save()
    
    [C#]
    Object file = 1;
    Application.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 is 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 want want to test to see if the file
    ' already exists. This will overwrite any previously 
    ' existing document with the specified name.
    Me.SaveAs("c:\test\MyNewDocument.doc")
    
    [C#]
    // Save the document. In a real application,
    // you want want to test to see if the file
    // already exists. This will overwrite any previously 
    // existing documents.
    Object fileName = @"C:\Test\MyNewDocument.doc";
    
    this.SaveAs(ref fileName,
      ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing);
    

Closing Documents

The Close method can be used to save documents as well as close them. You can close documents individually or close all at once.

  • Closing All Documents: The Close method works similarly to the Save method when applied to the Documents collection. When called with no arguments, it prompts the user to save changes to any unsaved documents.

    [Visual Basic]
    Application.Documents.Close()
    
    [C#]
    Application.Documents.Close(ref missing, 
        ref missing, ref missing);
    

    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.
    Application.Documents.Close( _
      Word.WdSaveOptions.wdSaveChanges)
    
    ' Closes all documents: does not save any changes.
    Application.Documents.Close( _
      Word.WdSaveOptions.wdDoNotSaveChanges)
    
    [C#]
    // Closes all documents: saves with no prompt.
    Object saveChanges = Word.WdSaveOptions.wdSaveChanges;
    Application.Documents.Close(ref saveChanges, 
        ref missing, ref missing);
    
    // Closes all documents: does not save any changes.
    Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
    Application.Documents.Close(ref saveChanges, 
        ref missing, ref missing);
    

    **Note   **When you call the Application.Quit method, Word shuts down. Closing all open documents does not cause Word to quit. If you close all open documents, Word will still be running and you still need to shut it down.

  • Close a Single Document: The code fragments listed here close the document without saving changes, and close MyNewDocument silently saving changes:

    [Visual Basic]
    ' Close the document without saving changes.
    Me.Close( _
      Word.WdSaveOptions.wdDoNotSaveChanges)
    
    'Close MyNewDocument and save changes without prompting.
    Application.Documents("MyNewDocument.doc").Close( _
      Word.WdSaveOptions.wdSaveChanges)
    
    [C#]
    // Close the document without saving changes.
    Object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
    this.Close(ref saveChanges, 
        ref missing, ref missing);
    
    // Close MyNewDocument and save changes without prompting.
    Object name = "MyNewDocument.doc";
    saveChanges = Word.WdSaveOptions.wdSaveChanges;
    
    Word.Document doc = Application.Documents.get_Item(ref name);
    this.Close(ref saveChanges, 
        ref missing, ref missing);
    

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 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) or foreach (in C#) loop to iterate through the documents. Inside the loop, you can conditionally perform operations on selected files. In this example, the code walks through all open documents, and if a document has not been saved, saves it.

The code in the sample procedure takes the following actions:

  • Loops through the collection of open documents.
  • Checks the Saved property of each document and saves the document if it 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 SaveUnsavedDocuments()
    ' Iterate through the Documents collection.
    Dim str As String
    Dim doc As Word.Document
    Dim sw As New StringWriter

    For Each doc In Application.Documents
        If 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 Application.Documents)
    {
        if (!doc.Saved) 
        {
            // Save the document.
            doc.Save();
            sw.WriteLine(doc.Name);
        }
    } 

    str = sw.ToString();
    if ( str == string.Empty ) 
    {
    str = "No documents 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 and then perform the operation. You can use the Selection object to select, format, manipulate, and print text in your document.

The Selection object is always present in a document. If nothing is selected, it represents the insertion point. Therefore, it is 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 the Selection 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 is important to know what, if anything, is selected. For example, if you are performing an operation on a column in a table, you want 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 for each of the enumerations is obvious given its name, for the most part, but some are a little more obscure. For example, wdSelectionIP represents the insertion point. The wdInlineShape value represents an image or a picture. The value wdSelectionNormal represents selected text, or a combination of text and other selected objects.

The code in the following procedure works with the Selection's Type property in order to determine the type of selection. To test it, enter and select some text within the sample document, then run the demo form. The code 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 Application.Selection.Type
        Case 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.wdNoSelection
            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 (Application.Selection.Type) 
    {
        case Word.WdSelectionType.wdSelectionBlock:
            str = "block";
            break;
        case Word.WdSelectionType.wdSelectionColumn:
            str = "column";
            break;
        case Word.WdSelectionType.wdSelectionFrame:
            str = "frame";
            break;
        case Word.WdSelectionType.wdSelectionInlineShape:
            str = "inline shape";
            break;
        case Word.WdSelectionType.wdSelectionIP:
            str = "insertion point";
            break;
        case Word.WdSelectionType.wdSelectionNormal:
            str = "normal text";
            break;
        case Word.WdSelectionType.wdNoSelection:
            str = "no selection";
            break;
        case Word.WdSelectionType.wdSelectionRow:
            str = "row";
            break;
        default:
            str = "(unknown)";
            break;
    }
    MessageBox.Show(str, "ShowSelectionType");
}

In addition to determining what is 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 as if you pressed the HOME key on the keyboard.

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

You use one of the following wdUnits enumerations for the Unit argument, which determines the range of the move:

  • WdLine: Move to the beginning or the end of a line. This is the default value.
  • WdStory: Move to the beginning or the end of the document.
  • WdColumn: Move to the beginning or end of a column. Valid for tables only.
  • WdRow: Move to the beginning or the end of a row. Valid for tables only.

You use one of the following WdMovementType enumerations for the Extend argument, which determines whether the Selection object is an extended range or the insertion point:

  • WdMove: Moves the selection. The 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 result is that the new Selection object consists of a range that extends from the insertion point to the endpoint. 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 is not included in the new selection. If the EndKey method is called with the wdStory and wdExtend enumerations, the line is included in the selection. This behavior mirrors the keyboard shortcuts CTRL+SHIFT+HOME and CTRL+SHIFT+END, respectively.

The following code moves the insertion point to the beginning of the document using the HomeKey method with the wdStory and the WdMovementType wdMove enumerations. The code then extends the selection to the end of the document using the EndKey with the wdExtend enumeration:

[Visual Basic]
' Position the insertion point at the beginning of the document.
Application.Selection.HomeKey( _
  Word.WdUnits.wdStory, Word.WdMovementType.wdMove)

' Select from the insertion point to the end of the document.
Application.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;
Application.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;
Application.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 enumerations for the Unit argument for MoveLeft and MoveRight:

  • wdCharacter: Move in character increments. This is the default value.
  • wdWord: Move in word increments.
  • wdCell: Move in cell increments. Valid for tables only.
  • wdSentence: Move in sentence increments.

The following code fragment moves the insertion point to the left three characters, and then selects the three words to the right of the insertion point.

[Visual Basic]
' Move the insertion point left 3 characters.
Application.Selection.MoveLeft( _
  Word.WdUnits.wdCharacter, 3, _
  Word.WdMovementType.wdMove)

' Select the 3 words to the right of the insertion point.
Application.Selection.MoveRight( _
  Word.WdUnits.wdWord, 3, _
  Word.WdMovementType.wdExtend)

[C#]
// Move the insertion point left 3 characters.
Object unit = Word.WdUnits.wdCharacter;
Object count = 3;
Object extend = Word.WdMovementType.wdMove;
Application.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;
Application.Selection.MoveRight(ref unit, ref count, 
    ref extend);

The MoveUp and MoveDown methods take the following enumerations for WdUnits:

  • wdLine: Moves in line increments. This is the default value.
  • wdParagraph: Moves in paragraph increments.
  • wdWindow: Moves in window increments.
  • wdScreen: Moves in screen increments.

The following code fragment moves the insertion point up one line, and then selects the three following paragraphs. What is actually 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.
Application.Selection.MoveUp( _
 Word.WdUnits.wdLine, 1, Word.WdMovementType.wdMove)

' Select the following 3 paragraphs.
Application.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;
Application.Selection.MoveUp(ref unit, ref count, ref extend);

// Select the following 3 paragraphs.
unit = Word.WdUnits.wdParagraph;
count = 3;
extend = Word.WdMovementType.wdMove;
Application.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 result is an insertion point at the beginning of the third word, not the third word itself:

[Visual Basic]
Application.Selection.Move(Word.WdUnits.wdWord, 3)

[C#]
// Use the Move method to move 3 words.
Obiect unit = Word.WdUnits.wdWord;
Object count = 3;
Application.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 activated, any text next to the insertion point is overwritten:

[Visual Basic]
Friend Sub InsertTextAtSelection()
    Dim sln As Word.Selection = Application.Selection

    ' Make sure overtype is turned off.
  Application.Options.Overtype = False

[C#]
public void InsertTextAtSelection() 
{
    Word.Selection sln = Application.Selection;

    // Make sure overtype is turned off.
  Application.Options.Overtype = false;

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

[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.wdSelectionIP ) 
{
    sln.TypeText("Inserting at insertion 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 mark are then inserted:

[Visual Basic]
    ElseIf .Type = Word.WdSelectionType.wdSelectionNormal Then
        ' Move to start of selection.
            If Application.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.
        if ( Application.Options.ReplaceSelection ) 
        {
            Object direction = Word.WdCollapseDirection.wdCollapseStart;
            sln.Collapse(ref direction);
        }
        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 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 is a range that consists of an insertion point. Or you can define a range that encompasses the entire document by starting at the first character and including the last character. Note that the range also includes all non-printing characters, such as spaces, tabs, and paragraph marks.

**Note   **The ranges you create are 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 document.
  • The Range object has greater capabilities than the Selection object, as you 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 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 is not selected in the Word user interface, but you still can manipulate it programmatically.

[Visual Basic]
Dim rng As Word.Range = Me.Range(0, 7)
rng.Select()

[C#]
Object start = 0;
Object end = 7;
Word.Range rng = this.Range(ref start, ref end);
rng.Select();

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

A Range object includes non-printing characters

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 = _
  Me.Range(0, Me.Characters.Count)
'Or use:
' rng = Me.Range()
rng.Select()
MessageBox.Show( _
  "Characters: " & Me.Characters.Count.ToString)

[C#]
Word.Range rng = this.Range(ref missing, ref missing);
rng.Select();
MessageBox.Show("Characters: " + 
    this.Characters.Count.ToString());

**Tip   **In Visual Basic, 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 do not care about the number of characters and all you want to do is to select the entire document, you can use the Document object's Select method on its Range property:

[Visual Basic]
Me.Range.Select()

[C#]
Word.Range rng = this.Range(ref missing, ref missing);
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 = Me.Content
rng.Select()

[C#]
Word.Range rng = this.Content;

You can also use the methods and properties of other objects to determine a range. The code in the next procedure takes the following actions to select the second sentence in the document:

  • Creates a Range variable
  • Checks to see if there are at least two sentences in the document
  • Sets the Start argument of the Range method to the start of the second sentence
  • Sets the End argument of the Range method to the end of the second sentence
  • Selects the range
[Visual Basic]
Friend Sub SelectSentence()
    Dim rng As Word.Range
    With Me
        If .Sentences.Count >= 2 Then
            ' Supply a Start and End value for the Range.
            rng = .Range( _
             CType(.Sentences(2).Start, System.Object), _
             CType(.Sentences(2).End, System.Object))
            ' Select the Range.
            rng.Select()
        End If
    End With
End Sub

//C
public void SelectSentence() 
{
  Word.Range rng;

    if (this.Sentences.Count >= 2 ) 
    {
        // Supply a Start and end value for the Range.
        Object start = this.Sentences[2].Start;
        Object end = this.Sentences[2].End;
        rng = this.Range(ref start, ref end);
        rng.Select();
    }
}

**Note   **The parameters passed to the Range property are declared as System.Object, so the code must convert these values explicitly. If you are working in Visual Basic with Option Strict set to Off, this is not necessary. If you are working in C#, you must pass these values by reference.

**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 = Me.Sentences(2)
rng.Select()

[C#]
Word.Range rng = this.Sentences[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
  • wdParagraph
  • wdSection
  • wdStory
  • wdCell
  • wdColumn
  • wdRow
  • wdTable

The Count argument specifies the number of the units to move. The following code defines a range consisting of the first seven characters in the document. The code then uses the Range object's MoveStart method to move the starting point of the range by seven characters. Because the end of the range is also seven characters, the result is a range consisting of the insertion point. The code then moves the ending position by seven characters using the MoveEnd method.

[Visual Basic]
' Define a range of 7 characters.
Dim rng As Word.Range = _
  Me.Range(0, 7)

' Move the starting position 7 characters.
rng.MoveStart(Word.WdUnits.wdCharacter, 7)

' Move the ending position 7 characters.
rng.MoveEnd(Word.WdUnits.wdCharacter, 7)

[C#]
// Define a range of 7 characters.
Object start = 0;
Object end = 7;
Word.Range rng = this.Range(ref start, ref end);

// Move the starting position 7 characters.
Object unit = Word.WdUnits.wdCharacter;
Object count = 7;
rng.MoveStart(ref unit, ref count);

// Move the ending position 7 characters.
unit = Word.WdUnits.wdCharacter;
count = 7;
rng.MoveEnd(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 moved the starting position by seven characters (the range is an insertion point, displayed as an I-bar). The third line displays the characters selected after the MoveEnd statement moves the end of the range by seven characters.

Using the MoveStart and MoveEnd methods to resize a range

Figure 10. Using the MoveStart and MoveEnd 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 SetRange 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 = Me.Range(0, 7)
' Reset the existing Range.
rng.SetRange( _
 Me.Sentences(2).Start, _
 Me.Sentences(5).End)

[C#]
Word.Range rng;
Object start = 0;
Object end = 7;
rng = this.Range(ref start, ref end);

// Reset the existing Range.
rng.SetRange(this.Sentences[2].Start, 
    this.Sentences[5].End);
rng.Select();

Formatting Text

You can also use the Range object to format text. The steps you need to take in your code are:

  • Define the range to format.
  • Apply the formatting.
  • Optionally select the formatted range to display it.

The code in the sample procedure selects the first paragraph in the document and changes the font size, font name, and the alignment. It then selects the range and displays a MessageBox to pause before executing the next section of code, which calls the Document object's Undo method three times. The next code block applies the Normal Indent style and displays a MessageBox to pause the code. Then the code calls the Undo method once, and displays a MessageBox.

[Visual Basic]
Friend Sub FormatRangeAndUndo()
    ' Set the Range to the first paragraph.
    Dim rng As Word.Range = _
      Me.Paragraphs(1).Range

    ' Change the formatting.
    With rng
        .Font.Size = 14
        .Font.Name = "Arial"
        .ParagraphFormat.Alignment = _
           Word.WdParagraphAlignment.wdAlignParagraphCenter
    End With
    rng.Select()
    MessageBox.Show("Formatted Range", "FormatRangeAndUndo")

    ' Undo the three previous actions.
    Me.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.
    Me.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 = this.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;
    this.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;
    this.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 either the name of the style or a Style object by reference to the set_Style method in order to apply a style to the range. In cases in which a read/write property is defined as a Variant in VBA, C# developers must call the appropriate hidden accessor methods, like set_Style and get_Style. Visual Basic developers can simply set or get the value of the property directly.

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 then selects the Range, which now includes the inserted text. Figure 11 shows the results after the code has run.

[Visual Basic]
Dim str As String = "New Text"
Dim rng As Word.Range = Me.Range(0, 0)
rng.Text = str
rng.Select()

[C#]
string  str = " new Text ";
Object start = 0;
Object end = 0;
Word.Range rng = this.Range(ref start, ref end);
rng.Text = str;
rng.Select();

Inserting new text at an insertion point

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 = Me.Range(0, 12)
rng.Text = str
rng.Select()

[C#]
start = 0;
end = 12;
rng = this.Range(ref start, ref end);
rng.Text = str;
rng.Select();

Inserting new text over existing text

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 then uses the wdCollapseStart enumeration to collapse the range. Next, it inserts the new text and selects the range. Figure 13 shows the results.

[Visual Basic]
Dim str As String = " New Text "
Dim rng As Word.Range = _
  Me.Paragraphs(1).Range
rng.Collapse(Word.WdCollapseDirection.wdCollapseStart)
rng.Text = str
rng.Select()

[C#]
string  str = " new Text ";
Word.Range rng = this.Paragraphs[1].Range;
Object direction = Word.WdCollapseDirection.wdCollapseStart;
rng.Collapse(ref direction);
rng.Text = str;
rng.Select();

The text you insert after collapsing a paragraph range is inserted at the beginning of the paragraph

Figure 13. The text you insert after collapsing a paragraph range is inserted at the beginning of the paragraph

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

[Visual Basic]
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)

[C#]
Object direction = Word.WdCollapseDirection.wdCollapseEnd;
rng.Collapse(ref direction);

Collapsing the end of a paragraph inserts text in the next paragraph

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

[Visual Basic]
Friend Sub ManipulateRangeText()
    ' Retrieve contents of first and second paragraphs
    Dim str1 As String = Me.Paragraphs(1).Range.Text
    Dim str2 As String = Me.Paragraphs(2).Range.Text

[C#]
public void ManipulateRangeText() 
{
    // Retrieve contents of first and second paragraphs
    string  str1 = this.Paragraphs[1].Range.Text;
    string  str2 = this.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 = _
      Me.Paragraphs(1).Range
    rng1.Text = str2

    Dim rng2 As Word.Range = _
      Me.Paragraphs(2).Range
    rng2.Text = str1

    ' Pause to display the results.
    rng1.Select()
    MessageBox.Show(rng1.Text, "ManipulateRangeText")
    rng2.Select()
    MessageBox.Show(rng2.Text, "ManipulateRangeText")

[C#]
    // Swap the paragraphs.
    Word.Range rng1 = this.Paragraphs[1].Range;
    rng1.Text = str2;

    Word.Range rng2 = this.Paragraphs[2].Range;
    rng2.Text = str1;

    // Pause to display the results.
    rng1.Select();
    MessageBox.Show(rng1.Text, "ManipulateRangeText");
    rng2.Select();
    MessageBox.Show(rng2.Text, "ManipulateRangeText");

The first and second paragraphs have been swapped, and rng1 is selected

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

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.MoveEnd(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.MoveEnd(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 highlighted; it is merged 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, "ManipulateRangeText")
    rng2.Select()
    MessageBox.Show(rng2.Text, "ManipulateRangeText")

[C#]
    // Pause to display the results.
    rng1.Select();
    MessageBox.Show(rng1.Text, "ManipulateRangeText");
    rng2.Select();
    MessageBox.Show(rng2.Text, "ManipulateRangeText");

The new content inserted in rng2 overwrote the paragraph mark

Figure 16. The new content inserted in rng2 overwrote the paragraph mark

Because the original contents of both ranges were saved as String variables, it is 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.MoveEnd(Word.WdUnits.wdCharacter, 1)

[C#]
  unit = Word.WdUnits.wdCharacter;
  count = 1;
  rng1.MoveEnd(ref unit, ref count);

The code then deletes rng2 entirely. This will restore the 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;

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

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

[Visual Basic]
  rng1.InsertAfter(str2)
  rng1.Select()
End Sub

[C#]
  rng1.InsertAfter(str2);
  rng1.Select();

}

The InsertAfter method extends the Range object to include the inserted text

Figure 17. The InsertAfter method extends the Range object to include the inserted 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 object as a named location in the document that is saved with the document.

In order to make it easier to work with Word bookmarks, Visual Studio 2005 Tools for Office adds the Bookmark host control. Using a host control allows you to set properties, call methods, and react to events of bookmarks—using the built-in Bookmark class provides none of these features. When you add a bookmark to a document at design time, Visual Studio 2005 Tools for Office automatically creates a Bookmark host control at the same time. You can write code that does not take into account the Bookmark host control, but working with Word becomes a lot simpler if you take advantage of these controls. One big difference that you find is that when you use a Bookmark host control, you simply set the Text property of the control to modify the text displayed within the bookmark. If you do not add a Bookmark host control, you must take several extra steps (discussed later in this section) in order to change the text inside the bookmark and preserve the bookmark. By default, without Visual Studio 2005 Tools for Office and its Bookmark host control, Word 2003 removes the bookmark when you modify its text.

Creating a Bookmark

You can, of course, create bookmarks using the Word 2003 user interface. Sometimes, however, you must create bookmarks programmatically, while an application or template is running. The Bookmarks collection exists as a member of the Document, Range, and Selection objects. The CreateBookmarks sample procedure shows how to create bookmarks in a document and use them for inserting text. This example uses the Controls.AddBookmark method of the document, which adds a Bookmark host control for each new bookmark. The Bookmark host control encapsulates the Word Bookmark class. In other words, it adds functionality, but leaves all the existing functionality intact. Your code can work with the Microsoft.Office.Interop.Word.Bookmark class, or the Microsoft.Office.Tools.Word.Bookmark host control.

The sample code takes the following actions:

  • Declares a Range and two Bookmark variables and sets the view's ShowBookmarks property to True. Setting this property causes a Bookmark object set as an insertion point to appear as a gray I-bar, and a Bookmark object set to a range of text to appear as gray brackets surrounding the bookmarked text.

    [Visual Basic]
    Friend Sub CreateBookmarks()
        Dim bookMk1 As Microsoft.Office.Tools.Word.Bookmark
        Dim bookMk2 As Microsoft.Office.Tools.Word.Bookmark
    
        ' Display Bookmarks
        Me.ActiveWindow.View.ShowBookmarks = True
        ' Code removed here. . .
    End Sub
    
    [C#]
    public void CreateBookmarks()
    {
        Microsoft.Office.Tools.Word.Bookmark bookMk1;
        Microsoft.Office.Tools.Word.Bookmark bookMk2;
    
        // Display Bookmarks
        this.ActiveWindow.View.ShowBookmarks = true;
        // Code removed here. . .
    }
    
  • Defines a Range object as the first insertion point at the beginning of the document

    [Visual Basic]
    Dim rng As Word.Range = Me.Range(0, 0)
    
    [C#]
    Object start = 0;
    Object end = 0;
    Word.Range rng = this.Range(ref start, ref end);
    
  • Adds a Bookmark host control named bookMk1 consisting of the Range object and displays a MessageBox to halt the execution of the code. At this point, you see the Bookmark object displayed as a faint I-bar to the left of the start of the paragraph, as shown in Figure 18.

    [Visual Basic]
    ' Add a Bookmark consisting of the Range object
    bookMk1 = Me.Controls. _
    AddBookmark(rng, "bookMk1")
    
    ' Display the bookmark
    MessageBox.Show("bookMk1 Text: " & _
    bookMk1.Text, "CreateBookmarks")
    
    [C#]
    // Add a Bookmark consisting of the Range object
    Object range = rng;
    bookMk1 = this.Controls.AddBookmark(rng, "bookMk1");
    
    // Display the bookmark
    MessageBox.Show("bookMk1 Text: " + 
        bookMk1.Text, "CreateBookmarks");
    

    A Bookmark object defined as an insertion point is displayed as an I bar

    Figure 18. A Bookmark object defined as an insertion point is displayed as an I-bar

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

    [Visual Basic]
    rng.InsertBefore("**InsertBefore bookMk1**")
    
    ' Show Bookmark code.
    MessageBox.Show("bookMk1 Text: " & bookMk1.Text, _
        "CreateBookmarks")
    
    [C#]
    // Insert text before the first Bookmark
    rng.InsertBefore("**InsertBefore bookMk1**");
    
    // Show Bookmark text
    MessageBox.Show("bookMk1 Text: " + 
     bookMk1.Text, "CreateBookmarks");
    

    The inserted text is included in the bookmark

    Figure 19. The inserted text is included in the bookmark

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

    [Visual Basic]
    rng.InsertAfter("**InsertAfter bookMk1**")
    MessageBox.Show("bookMk1 Text: " & bookMk1.Text, _
        "CreateBookmarks")
    
    [C#]
    rng.InsertAfter("**InsertAfter bookMk1**");
    MessageBox.Show("bookMk1 Text: " + bookMk1.Text, 
        "CreateBookmarks");
    

    Inserting text after the Bookmark object

    Figure 20. Inserting text after the Bookmark object

  • 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 object's brackets surrounding the second paragraph, as shown in Figure 21.

    [Visual Basic]
     rng = Me.Paragraphs(2).Range
    
    ' Create new Bookmark on paragraph 2
    bookMk2 = Me.Controls. _
    AddBookmark(rng, "bookMk2")
    MessageBox.Show("bookMk2 Text: " & bookMk2.Text, _
      "bookMk2 set")
    
    [C#]
     rng = this.Paragraphs[2].Range;
    
    // Create new Bookmark on paragraph 2
    bookMk2 = this.Controls.
        AddBookmark(rng, "bookMk2");
    MessageBox.Show("bookMk2 Text: " + bookMk2.Text,
      "bookMk2 set");
    

    A Bookmark object encompassing a range of text is displayed as opening and closing square brackets

    Figure 21. A Bookmark object encompassing a range of text is displayed as opening and closing square brackets

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

    [Visual Basic]
    rng.InsertBefore("**InsertBefore bookMk2**")
    MessageBox.Show("bookMk2 Text: " & bookMk2.Text, _
      "InsertBefore bookMk2")
    
    [C#]
    rng.InsertBefore("**InsertBefore bookMk2**");
    MessageBox.Show("bookMk2 Text: " + bookMk2.Text, 
      "InsertBefore bookMk2");
    

    When the Bookmark object is a range of text, the InsertBefore method adds it to the Bookmark

    Figure 22. When the Bookmark object is a range of text, the InsertBefore method adds it to the Bookmark

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

    [Visual Basic] 
    ' Insert text after.
    rng.InsertAfter("**InsertAfter bookMk2**")
    MessageBox.Show("bookMk2 Text: " & bookMk2.Text, _
      "InsertAfter bookMk2")
    
    bookMk2.Select()
    MessageBox.Show("bookMk2.Select()", "CreateBookmarks")
    
    [C#]
    rng.InsertAfter("**InsertAfter bookMk2**");
    MessageBox.Show("bookMk2 Text: " + bookMk2.Text, 
        "InsertAfter bookMk2");
    
    bookMk2.Select();
    MessageBox.Show("bookMk2.Select()", "CreateBookmarks");
    

    Text inserted after a Bookmark object is not included in the Bookmark

    Figure 23. Text inserted after a Bookmark object is not included in the Bookmark

**Tip   **The previous example took advantage of the Microsoft.Office.Tools.Word.Bookmark class, which provides a wrapper around the built-in Word.Bookmark class. Because the code used this host control, rather than the standard Bookmark class, it was able to create bookmarks without passing parameters by reference in C#, and it was able to retrieve the Text property of the Bookmark object directly, rather than needing to use the Range.Text property that is required when working with Word.Bookmark instances. The Bookmark host control makes programming bookmarks simpler, and you should consider using this wrapper class whenever you need to work with bookmarks.

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 object in the document and its Range.Text property using the MessageBox.Show method:

[Visual Basic]
Friend Sub ListBookmarks()
    Dim sw As New StringWriter
    Dim bmrk As Word.Bookmark

    For Each bmrk In Me.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 this.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 host control's text is easy. You simply assign a value to the Control's Text property. If you work with a Word bookmark directly, however, modifying the Range.Text property of the bookmark deletes the entire bookmark. There is no easy way to insert text into a standard Word bookmark so that you can retrieve the text later. The simplest solution is to use a Bookmark host control, as shown in the BookmarkText procedure. Figure 24 shows the results of running this procedure.

[Visual Basic]
Friend Sub BookmarkText()
    'Create a bookmark on the first paragraph
    Dim bkmrk As Microsoft.Office.Tools.Word.Bookmark
    Dim doc As Word.Document = Me.InnerObject

    bkmrk = Me.Controls.AddBookmark( _
     doc.Paragraphs(1).Range, "bkMark")
    ' Display Bookmark
    doc.ActiveWindow.View.ShowBookmarks = True
    MessageBox.Show(bkmrk.Text, _
     "BookmarkText")

    ' Replace the text within the bookmark host control:
    bkmrk.Text = "New Bookmark Text."
End Sub

[C#]
public void BookmarkText()
{
    // Create a bookmark on the first paragraph
    Word.Range rng = this.Paragraphs[1].Range;
    Microsoft.Office.Tools.Word.Bookmark bkmrk =
        this.Controls.AddBookmark(rng, "bkMark");

    // Display Bookmark
    this.ActiveWindow.View.ShowBookmarks = true;
    MessageBox.Show(bkmrk.Text, "BookmarkText");
    // Replace the text within the Bookmark host control:
    bkmrk.Text = "New Bookmark Text.";
}

The original Bookmark is replaced with new text

Figure 24. The original Bookmark is replaced with new text

Although you can always use a Bookmark host control rather than a Word Bookmark instance, if you do not want to use the host control, you need to find some way to preserve the bookmark yourself after you insert text. When you update the contents of a Bookmark, the solution is to reset the bookmark's 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 declares a Range object and sets it to the Bookmark object'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. (Remember, you only need to use this procedure ** if you do not want to use a Bookmark host control, which does not incur any special overhead of extra programming. This procedure is included here mostly for backward compatibility, because there is generally no reason why you would not want to use a Bookmark host control and avoid these issues.) The ReplaceBookmarkText procedure follows:

[Visual Basic]
Friend Sub ReplaceBookmarkText( _
  ByVal BookmarkName As String, _
  ByVal NewText As String)
    If Me.Bookmarks.Exists(BookmarkName) Then
        Dim rng As Word.Range = _
          Me.Bookmarks(BookmarkName).Range
        rng.Text = NewText
        Me.Bookmarks.Add( _
          BookmarkName, CType(rng, Word.Range))
    End If
End Sub

[C#]
public void ReplaceBookmarkText(string  BookmarkName, 
    string  NewText) 
{
    if (this.Bookmarks.Exists(BookmarkName)) 
    {
        Object name = BookmarkName;
        Word.Range rng = this.Bookmarks.
            get_Item(ref name).Range;
        rng.Text = NewText;
        Object range = rng;
        this.Bookmarks.Add(BookmarkName, ref range);
    }
}

You can call the procedure by passing the name of the Bookmark object 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.

The Find object is a member of both the Selection and the Range objects, and you can use either one to search for 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 is 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 FindInSelection()
    ' Move selection to beginning of doc.
    Application.Selection.HomeKey( _
        Word.WdUnits.wdStory, Word.WdMovementType.wdMove)

    Dim strFind As String = "dolor"
    Dim fnd As Word.Find = Application.Selection.Find
    fnd.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 FindInSelection()
{
    // Move selection to beginning of doc
    Object unit = Word.WdUnits.wdStory;
    Object extend = Word.WdMovementType.wdMove;
    Application.Selection.HomeKey(ref unit, ref extend);

    Word.Find fnd = Application.Selection.Find;
    fnd.ClearFormatting();

    Object findText = "dolor";

    if (fnd.Execute(ref findText, ref missing, ref missing,
      ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing,
      ref missing))
    {
        MessageBox.Show("Text found.", "FindInSelection");
    }
    else
    {
        MessageBox.Show("Text not found.", "FindInSelection");
    }
}

Found text is automatically selected when searching with a Selection object

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 the ClearFormatting 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&#151only; the syntax is different. Because you are 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 Application.Selection.Find
        .ClearFormatting()
        .Forward = True
        .Wrap = Word.WdFindWrap.wdFindContinue
        .Text = "ipsum"
        .Execute()
    End With

    ' Use Execute method arguments to specify search criteria.
    With Application.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 = Application.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 = Application.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, missing, missing);
}

private Boolean ExecuteFind(
  Word.Find find, Object wrapFind, Object forwardFind)
{
    // Simple wrapper around Find.Execute:
    Object forward = forwardFind;
    Object wrap = wrapFind;

    return find.Execute(ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing,
      ref forward, ref wrap, ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing,
      ref missing);
}

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, the search criteria is selected and displayed, as shown in Figure 26. The C# version of this example uses the ExecuteFind wrapper method discussed previously.

[Visual Basic]
Public Sub FindInRange()
    ' Set the second paragraph as the search range.
    Dim rng As Word.Range = _
      Me.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 is displayed if the
    ' search succeeds; paragraph 2 is displayed
    ' if the search fails.
  rng.Select()
End Sub

[C#]
public void FindInRange()
{
    // Set the second paragraph as the search range
    Word.Range rng = this.Paragraphs[2].Range;
    Word.Find fnd = rng.Find;

    // Clear existing formatting
    fnd.ClearFormatting();

    // Execute the search
    fnd.Text = "faucibus";
    if (ExecuteFind(fnd))
    {
        MessageBox.Show("Text found.", "FindInRange");
    }
    else
    {
        MessageBox.Show("Text not found.", "FindInRange");
    }

    // The word faucibus is displayed if the
    // search succeeds; paragraph 2 is displayed
    // if the search fails.
    rng.Select();
}

If the Range object's Find method succeeds, the range will be redefined to contain the search criteria

Figure 26. If the Range object's Find method succeeds, the range is redefined 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 document, changes the font color and bold properties for each match. It uses the Found property in a loop, and increments a counter each time the string is found. The code then displays the number of times the string was found in a MessageBox. The C# version of this demonstration uses the ExecuteFind method discussed previously.

[Visual Basic]
Public Sub FindInLoopAndFormat()
    Dim intFound As Integer
    Dim rngDoc As Word.Range = Me.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 searching range to be the found text.
        rngDoc.Font.Color = Word.WdColor.wdColorRed
        rngDoc.Font.Bold = 600
        intFound += 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 = this.Characters.Count;
    Word.Range rngDoc = this.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 searching range to be the found text.
        rngDoc.Font.Color = Word.WdColor.wdColorRed;
        rngDoc.Font.Bold = 600;
        intFound++;
        ExecuteFind(fnd);
    }
    MessageBox.Show(
      String.Format("lorem found {0} times.", 
      intFound), "FindInLoopAndFormat");
}

**Tip   **It may seem odd that the range, rngDoc, started out referring to the entire document's contents, but ends up referring to each match within the 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 need to keep a second variable that maintains the original information. In this case, because the original range was the entire document, it is easy to get that range reference back later, and there is 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 is 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 Application.Selection.Find
        .ClearFormatting()
        .Text = "Lorem"
        With .Replacement
            .ClearFormatting()
            .Text = "Forum"
        End With
        .Execute(Replace:=Word.WdReplace.wdReplaceAll)
    End With
End Sub

[C#]
public void SearchAndReplace() 
{
    // Move selection to beginning of document.
    Object unit = Word.WdUnits.wdStory;
    Object extend = Word.WdMovementType.wdMove;
    Application.Selection.HomeKey(ref unit, ref extend);

    Word.Find fnd = Application.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)
{
    return ExecuteReplace(find, Word.WdReplace.wdReplaceAll);
}

private Boolean ExecuteReplace(Word.Find find, 
 Object replaceOption)
{
    // Simple wrapper around Find.Execute:
    Object replace = replaceOption;
    return find.Execute(ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing,
      ref missing, ref missing, ref missing, ref missing, 
      ref replace,
      ref missing, ref missing, ref missing,
      ref missing);
}

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 = _
      Application.Selection.Range

    ' Define search range of entire document.
    Dim rngSearch As Word.Range = Me.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 = Application.Selection.Range;

    // Define search range of entire document
    Object start = 0;
    Object end = this.Characters.Count;
    Word.Range rngSearch = this.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 is very easy to work with the print engine to print entire documents or sections of documents.

Working with Print Preview

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

[Visual Basic]
Me.PrintPreview = True

[C#]
this.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 is displayed in normal view. If it is in normal view, it is displayed in Print Preview:

[Visual Basic]
Friend Sub TogglePrintPreview()
    Application.PrintPreview = Not Application.PrintPreview
End Sub

[C#]
public void TogglePrintPreview() 
{
    Application.PrintPreview = !Application.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 the document with all of the default options:

[Visual Basic]
Me.PrintOut()

[C#]
this.PrintOut(ref missing, ref missing,
    ref missing, ref missing, ref missing, ref missing, 
    ref missing, ref missing, ref missing, ref missing, 
    ref missing, ref missing, ref missing, 
    ref missing, ref missing, ref missing, 
    ref missing, ref missing);

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

Argument Description
Background Set to True to allow processing while Word prints the document
Append Use this with the OutputFileName argument. Set to True to append the specified document to the file name specified by the OutputFileName argument. Set to False to overwrite the contents of OutputFileName.
Range The page range. Can be any WdPrintOutRange enumeration: wdPrintAllDocument, wdPrintCurrentPage, wdPrintFromTo, wdPrintRangeOfPages, or wdPrintSelection
OutputFileName If PrintToFile is True, this argument specifies the path and file name of the output file.
From The starting page number when Range is set to wdPrintFromTo
To The ending page number when Range is set to wdPrintFromTo
Item The item to be printed. Can be any WdPrintOutItem enumeration: wdPrintAutoTextEntries, wdPrintComments, wdPrintDocumentContent, wdPrintKeyAssignments, wdPrintProperties, wdPrintStyles
Copies The number of copies to be printed
Pages The page numbers and page ranges to be printed, separated by commas. For example, "2, 6-10" prints page 2 and pages 6 through 10.
PageType The type of pages to be printed. Can be any WdPrintOutPages constant: wdPrintAllPages, wdPrintEvenPagesOnly, wdPrintOddPagesOnly
PrintToFile Set to True to send printer instructions to a file. Make sure to specify a file name with OutputFileName.
Collate Use when printing multiple copies of a document. Set to True to print all pages of the document before printing the next copy.
FileName Available only with the Application object. The path and file name of the document to be printed. If this argument is omitted, Word prints the document.
ManualDuplexPrint Set to True to print a two-sided document on a printer without a duplex printing kit.

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

[Visual Basic]
Friend Sub PrintOutDoc()
    Me.PrintOut( _
      Background:=True, _
      Append:=False, _
      Range:=Word.WdPrintOutRange.wdPrintCurrentPage, _
      Item:=Word.WdPrintOutItem.wdPrintDocumentContent, _
      Copies:=2, _
      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.WdPrintOutRange.wdPrintCurrentPage;
    Object item = Word.WdPrintOutItem.wdPrintDocumentContent;
    Object copies = 2;
    Object pageType = Word.WdPrintOutPages.wdPrintAllPages;
    Object printToFile = false;

    this.PrintOut(ref background, ref append,
      ref range, ref missing, ref missing, ref missing,
      ref item, ref copies, ref missing, ref pageType,
      ref printToFile, ref missing, ref missing,
      ref missing, ref missing,
      ref missing, ref missing,
      ref missing);
}

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 columns at the beginning of the document:

[Visual Basic]
Dim rng as Word.Range = _
  Me.Range(0, 0)
Me.Tables.Add(rng, 3, 4)

[C#]
Object start = 0;
Object end = 0;
Word.Range rng = this.Range(ref start, ref end);

this.Tables.Add(rng, 3, 4, ref missing,
    ref missing);

Working with a Table Object

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

[Visual Basic]
Dim tbl As Word.Table = Me.Tables(1)

[C#]
Word.Table tbl = this.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 Me.Tables(1)
    .Range.Font.Size = 8
    .Style = "Table Grid 8"
End With

[C#]
Word.Table tbl = this.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 Me.Tables (1)
    With .Cell(1, 1).Range
        .Text = "Name"
        .ParagraphFormat.Alignment = _
         Word.WdParagraphAlignment.wdAlignParagraphRight
    End With
End With

[C#]
Word.Range rng = this.Tables[1].Cell(1, 1).Range;
rng.Text = "Name";
rng.ParagraphFormat.Alignment =
    Word.WdParagraphAlignment.wdAlignParagraphRight;

Rows and Columns

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

[Visual Basic]
Dim tbl As Word.Table = Me.Tables(1)
tbl.Rows.Add()

[C#]
Word.Table tbl = this.Tables[1];
tbl.Rows.Add(ref missing);

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 = Me.Tables(1)
tbl.Columns.Add(tbl.Columns(1))
tbl.Columns.DistributeWidth

[C#]
Word.Table tbl = this.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 document and populates it with document properties:

[Visual Basic]
Public Sub CreateTable()
    ' Move to start of document.
    Dim rng As Word.Range = _
        Me.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( _
        Me.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 = Me.Words.Count.ToString
    tbl.Cell(3, 1).Range.Text = "Number of Characters"
    tbl.Cell(3, 2).Range.Text = _
      Me.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 = this.Range(ref start, ref end);

    // 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.
    Word.Table tbl = rng.Tables.Add(
      this.Paragraphs[2].Range, 3, 2,
      ref missing, ref missing);

    // 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).Range.Text =
      this.Words.Count.ToString();
    tbl.Cell(3, 1).Range.Text = "Number of Characters";
    tbl.Cell(3, 2).Range.Text =
      this.Characters.Count.ToString();
    tbl.Select();
}

Conclusion

Word has a rich object model that enables you to control Word programmatically and create documents from managed code. This article has only touched upon what is available. To investigate further, see the Word VBA Help file. With the information from this article, you can address almost any task involving document creation and production.

Additional Resources

Visual Studio 2005 Tools for Office

Office Developer Center

About the Author

Ken Getz is a developer, writer, and trainer, working as a senior consultant with MCW Technologies, LLC, a Microsoft Solution Provider. He has co-authored several technical books for developers, including the best-selling ASP.NET Developer's Jumpstart, the Access Developer's Handbook series, and the VBA Developer's Handbook series. Ken co-authored AppDev's C#, ASP.NET, Visual Basic .NET, and ADO.NET courseware. Ken is a technical editor for Advisor Publications' VB.NET Technical Journal, and he is a columnist for both MSDN Magazine and CoDe magazine. Ken speaks regularly at a large number of industry events, including Advisor Media's Advisor Live events, FTP's VSLive, DevConnection's VS and ASP Connections, and the annual Tech-Ed conference hosted by Microsoft.