如何:折叠文档中的范围或选定内容
更新:2007 年 11 月
适用对象 |
---|
本主题中的信息仅适用于指定的 Visual Studio Tools for Office 项目和 Microsoft Office 版本。 项目类型
Microsoft Office 版本
有关更多信息,请参见按应用程序和项目类型提供的功能。 |
如果您在使用 Range 对象或 Selection 对象,则可能需要在插入文本前将选定内容更改为插入点,以免覆盖现有文本。Range 和 Selection 对象都有一个 Collapse 方法,此方法使用 WdCollapseDirection 枚举值:
wdCollapseStart - 将选定内容折叠到选定内容的开头。如果未指定枚举值,则这是默认设置。
wdCollapseEnd - 将选定内容折叠到选定内容的结尾。
折叠范围并插入文本
创建一个包含文档中第一个段落的 Range 对象。
下面的代码示例可用于文档级自定义项。
Dim rng As Word.Range = Me.Paragraphs(1).Range
Word.Range rng = this.Paragraphs[1].Range;
下面的代码示例可用于应用程序级外接程序。此代码使用活动文档。
Dim rng As Word.Range = Me.Application.ActiveDocument.Paragraphs(1).Range
Word.Range rng = this.Application.ActiveDocument.Paragraphs[1].Range;
使用 wdCollapseStart 枚举值折叠范围。
rng.Collapse(Word.WdCollapseDirection.wdCollapseStart)
object direction = Word.WdCollapseDirection.wdCollapseStart; rng.Collapse(ref direction);
插入新文本。
rng.Text = " New Text "
rng.Text = " New Text ";
选择 Range。
rng.Select()
rng.Select();
如果使用 wdCollapseEnd 枚举值,文本将插入到下一段的开头。
rng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
direction = Word.WdCollapseDirection.wdCollapseEnd;
rng.Collapse(ref direction);
您也许以为插入新句子时会将其插入在段落标记的前面,但事实并非如此,因为原范围中包含段落标记。有关更多信息,请参见 如何:创建范围时排除段落标记。
文档级自定义项示例
在文档级自定义项中折叠范围
下面的示例显示了文档级自定义项的完整方法。若要使用此代码,请从项目内的 ThisDocument 类中运行此代码。
Dim rng As Word.Range = Me.Paragraphs(1).Range rng.Collapse(Word.WdCollapseDirection.wdCollapseStart) rng.Text = " New Text " rng.Select()
Word.Range rng = this.Paragraphs[1].Range; object direction = Word.WdCollapseDirection.wdCollapseStart; rng.Collapse(ref direction); rng.Text = " New Text "; rng.Select();
应用程序级外接程序示例
在应用程序级外接程序中折叠范围
下面的示例显示了应用程序级外接程序的完整方法。若要使用此代码,请从项目内的 ThisAddIn 类中运行此代码。
Dim rng As Word.Range = Me.Application.ActiveDocument.Paragraphs(1).Range rng.Collapse(Word.WdCollapseDirection.wdCollapseStart) rng.Text = " New Text " rng.Select()
Word.Range rng = this.Application.ActiveDocument.Paragraphs[1].Range; object direction = Word.WdCollapseDirection.wdCollapseStart; rng.Collapse(ref direction); rng.Text = " New Text "; rng.Select();