以编程方式设置文档中的文本格式

你可以使用 Range 对象来格式化 Microsoft Office Word 文档中的文本。

适用于: 本主题中的信息适用于 Word 的文档级项目和 VSTO 外接程序项目。 有关详细信息,请参阅办公室应用程序和项目类型提供的功能。

下面的示例选择文档中的第一个段落并更改字号、字体名称和对齐方式。 然后,它会选择范围并显示一个消息框,以在执行下一段代码前暂停。 下一部分调用主机项的 Document 撤消方法(用于文档级自定义)或 Document 类(对于 VSTO 外接程序)三次。 它应用“正文缩进”样式,并显示一个消息框以暂停代码。 然后,该代码调用 Undo 方法一次,并显示一个消息框。

文档级自定义示例

使用文档级自定义项格式化文本

  1. 可以在文档级自定义项中使用下面的示例。 若要使用此代码,请从项目中的 ThisDocument 类运行它。

    private void RangeFormat() 
    { 
        // Set the Range to the first paragraph. 
        Word.Range rng = this.Paragraphs[1].Range;
    
        // Change the formatting. To change the font size for a right-to-left language, 
        // such as Arabic or Hebrew, use the Font.SizeBi property instead of Font.Size.
        rng.Font.Size = 14; 
        rng.Font.Name = "Arial"; 
        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
    
        rng.Select(); 
        MessageBox.Show("Formatted Range"); 
    
        // Undo the three previous actions. 
        object numTimes3 = 3; 
        this.Undo(ref numTimes3); 
    
        rng.Select(); 
        MessageBox.Show("Undo 3 actions"); 
    
        // Apply the Normal Indent style. 
        object indentStyle = "Normal Indent"; 
        rng.set_Style(ref indentStyle); 
    
        rng.Select(); 
        MessageBox.Show("Normal Indent style applied"); 
    
        // Undo a single action. 
        object numTimes1 = 1; 
        this.Undo(ref numTimes1); 
    
        rng.Select(); 
        MessageBox.Show("Undo 1 action"); 
    }
    

VSTO 外接程序示例

使用 VSTO 外接程序格式化文本

  1. 可以在 VSTO 外接程序中使用下面的示例。 本示例使用活动文档。 若要使用此代码,请从项目中的 ThisAddIn 类运行它。

    private void RangeFormat()
    {
        // Set the Range to the first paragraph. 
        Word.Document document = this.Application.ActiveDocument;
        Word.Range rng = document.Paragraphs[1].Range;
    
        // Change the formatting. To change the font size for a right-to-left language, 
        // such as Arabic or Hebrew, use the Font.SizeBi property instead of Font.Size.
        rng.Font.Size = 14;
        rng.Font.Name = "Arial";
        rng.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
    
        rng.Select();
        MessageBox.Show("Formatted Range");
    
        // Undo the three previous actions. 
        object numTimes3 = 3;
        document.Undo(ref numTimes3);
    
        rng.Select();
        MessageBox.Show("Undo 3 actions");
    
        // Apply the Normal Indent style. 
        object indentStyle = "Normal Indent";
        rng.set_Style(ref indentStyle);
    
        rng.Select();
        MessageBox.Show("Normal Indent style applied");
    
        // Undo a single action. 
        object numTimes1 = 1;
        document.Undo(ref numTimes1);
    
        rng.Select();
        MessageBox.Show("Undo 1 action");
    }