以程式設計方式在 Word 文件中插入文字
在 Microsoft Office Word 文件中插入文字的方式主要有三種:
適用對象:本主題資訊適用於文件層級的專案和 Word 的 VSTO 增益集專案。 如需詳細資訊,請參閱依 Office 應用程式和專案類型提供的功能。
注意
有興趣開發跨多個平台擴充 Office 體驗的解決方案嗎? 查看新的 Office 增益集模型。 相較於 VSTO 增益集和解決方案,Office 增益集的使用量非常小,而且可以使用 HTML5、JavaScript、CSS3 和 XML 等幾乎任何 Web 程式設計技術來建置。
在範圍中插入文字
若要在範圍中插入文字
在文件的開頭指定範圍,並插入文字 New Text。
下列程式碼範例可用於文件層級自訂。
object start = 0; object end = 0; Word.Range rng = this.Range(ref start, ref end); rng.Text = "New Text";
下列程式碼範例可用於 VSTO 增益集。 這個程式碼會使用現用的文件。
選取 Range 物件,這時物件已從一個字元擴展為所插入文字的長度。
取代範圍中的文字
如果指定的範圍包含文字,則範圍內的所有文字都會以插入的文字取代。
若要取代範圍中的文字
建立一個包含文件中前 12 個字元的 Range 物件。
下列程式碼範例可用於文件層級自訂。
下列程式碼範例可用於 VSTO 增益集。 這個程式碼會使用現用的文件。
以 New Text字串取代這些字元。
選取範圍。
使用 TypeText 插入文字
TypeText 方法會在選取範圍插入文字。 TypeText 的行為方式會因使用者電腦上設定的選項而異。 下列程序中的程式碼宣告了 Selection 物件變數,並且關閉 Overtype 選項 (如果是開啟的)。 如果啟用 Overtype 選項,則會覆寫游標後面的任何文字。
若要使用 TypeText 方法插入文字
宣告 Selection 物件變數。
關閉 Overtype 選項 (如果是開啟的)。
測試目前的選取範圍是否為插入點。
如果是,程式碼就會使用 TypeText插入句子,然後使用 TypeParagraph 方法插入段落標記。
ElseIf 區塊中的程式碼會進行測試,檢查選取範圍是否為一般的選取範圍。 如果是,則另一個 If 區塊就會測試 ReplaceSelection 選項是否已開啟。 如果該選項已開啟,程式碼就會使用選取範圍的 Collapse 方法,將選取範圍摺疊至文字選取區塊起始處的插入點。 插入文字和段落標記。
else if (currentSelection.Type == Word.WdSelectionType.wdSelectionNormal) { // Move to start of selection. if (Application.Options.ReplaceSelection) { object direction = Word.WdCollapseDirection.wdCollapseStart; currentSelection.Collapse(ref direction); } currentSelection.TypeText("Inserting before a text block. "); currentSelection.TypeParagraph(); }
如果選取範圍不是插入點或選取文字的區塊,則 Else 區塊中的程式碼不會執行任何動作。
您也可以使用 Selection 物件的 TypeBackspace 方法,這個方法會模仿鍵盤上退格鍵 (BACKSPACE) 的功能。 但是,如果要插入和處理文字, Range 物件可以讓您有更多的控制能力。
下列範例顯示完整程式碼。 若要使用這個範例,請從專案中的
ThisDocument
或ThisAddIn
類別中執行程式碼。private void SelectionInsertText() { Word.Selection currentSelection = Application.Selection; // Store the user's current Overtype selection bool userOvertype = Application.Options.Overtype; // Make sure Overtype is turned off. if (Application.Options.Overtype) { Application.Options.Overtype = false; } // Test to see if selection is an insertion point. if (currentSelection.Type == Word.WdSelectionType.wdSelectionIP) { currentSelection.TypeText("Inserting at insertion point. "); currentSelection.TypeParagraph(); } else if (currentSelection.Type == Word.WdSelectionType.wdSelectionNormal) { // Move to start of selection. if (Application.Options.ReplaceSelection) { object direction = Word.WdCollapseDirection.wdCollapseStart; currentSelection.Collapse(ref direction); } currentSelection.TypeText("Inserting before a text block. "); currentSelection.TypeParagraph(); } else { // Do nothing. } // Restore the user's Overtype selection Application.Options.Overtype = userOvertype; }