以程式設計方式在文件中設定文字格式
您可以使用 Range 物件格式化 Microsoft Office Word 文件中的文字。
適用對象:本主題資訊適用於文件層級的專案和 Word 的 VSTO 增益集專案。 如需詳細資訊,請參閱依 Office 應用程式和專案類型提供的功能。
下列範例會選取文件中的第一個段落,並變更字型大小、字型名稱和對齊方式。 它接著會選取範圍,並顯示訊息方塊以在執行下個區塊的程式碼之前暫停。 下一節將呼叫 Document 主項目 (對於文件層級自訂) 或 Document 類別 (對於 VSTO 增益集) 的 Undo 方法三次。 它套用一般縮排樣式,並顯示訊息方塊以暫停程式碼。 接著,程式碼會呼叫 Undo 方法一次,並顯示訊息方塊。
文件層級自訂範例
使用文件層級自訂格式化文字
下列範例可以用於文件層級自訂。 若要使用此程式碼,請從專案的
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 增益集格式化文字
下列範例可以用於 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"); }