如何:在搜索后还原选定内容
更新:2007 年 11 月
适用对象 |
---|
本主题中的信息仅适用于指定的 Visual Studio Tools for Office 项目和 Microsoft Office 版本。 项目类型
Microsoft Office 版本
有关更多信息,请参见按应用程序和项目类型提供的功能。 |
如果查找并替换文档中的文本,在搜索结束后可能需要还原用户原来的选择。
示例过程中的代码使用了两个 Range 对象。一个存储当前的 Selection,另一个将整个文档设置为搜索范围。
搜索后恢复用户原来的选择
为文档和当前选择创建 Range 对象。
Dim start As Word.Range = Application.Selection.Range Dim searchArea As Word.Range = Application.ActiveDocument.Range
Word.Range start = Application.Selection.Range; Word.Range searchArea = Application.ActiveDocument.Range(ref missing, ref missing);
执行搜索和替换操作。
searchArea.Find.ClearFormatting() searchArea.Find.Text = "find me" searchArea.Find.Replacement.ClearFormatting() searchArea.Find.Replacement.Text = "Found" searchArea.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll)
searchArea.Find.ClearFormatting(); searchArea.Find.Text = "find me"; searchArea.Find.Replacement.ClearFormatting(); searchArea.Find.Replacement.Text = "Found"; object replaceAll = Word.WdReplace.wdReplaceAll; searchArea.Find.Execute( ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing);
选择要还原用户原来的选择的开始范围。
start.Select()
start.Select();
下面的示例演示完整的方法。
示例
Friend Sub ReplaceRestoreSelection()
Dim start As Word.Range = Application.Selection.Range
Dim searchArea As Word.Range = Application.ActiveDocument.Range
searchArea.Find.ClearFormatting()
searchArea.Find.Text = "find me"
searchArea.Find.Replacement.ClearFormatting()
searchArea.Find.Replacement.Text = "Found"
searchArea.Find.Execute(Replace:=Word.WdReplace.wdReplaceAll)
start.Select()
End Sub
internal void ReplaceRestoreSelection()
{
Word.Range start = Application.Selection.Range;
Word.Range searchArea = Application.ActiveDocument.Range(ref missing, ref missing);
searchArea.Find.ClearFormatting();
searchArea.Find.Text = "find me";
searchArea.Find.Replacement.ClearFormatting();
searchArea.Find.Replacement.Text = "Found";
object replaceAll = Word.WdReplace.wdReplaceAll;
searchArea.Find.Execute(
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing, ref missing, ref missing);
start.Select();
}