This documentation is archived and is not being maintained.

How to: Format Text in Documents


Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

This example demonstrates how to use the Range object to format text in a Microsoft Office Word 2003 document. It demonstrates selecting the first paragraph in the document and changing the font size, the font name, and the alignment. It then demonstrates selecting the range and displaying a message box to pause before executing the next section of code, which calls the Undo method of the Document three times. It applies the Normal Indent style and displays a message box to pause the code. Then the code calls the Undo method once, and displays a message box.


You will notice that you write less formatting code if you define styles for all of your formatting needs. In addition, styles are easier to maintain. If you need to change the formatting of a document, you only need to do it in one place (the style), so you do not need to search and replace through your code.


private void RangeFormat() 
    // 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;

    MessageBox.Show("Formatted Range"); 

    // Undo the three previous actions. 
    object numTimes3 = 3; 
    this.Undo(ref numTimes3); 

    MessageBox.Show("Undo 3 actions"); 

    // Apply the Normal Indent style. 
    object indentStyle = "Normal Indent"; 
    rng.set_Style(ref indentStyle); 

    MessageBox.Show("Normal Indent style applied"); 

    // Undo a single action. 
    object numTimes1 = 1; 
    this.Undo(ref numTimes1); 

    MessageBox.Show("Undo 1 action"); 

See Also