如何:在 Word 文档中搜索文本

2008年11月1日星期六

如何:在 Word 文档中搜索文本

Find 对象既是 Selection 的成员,又是 Range 对象的成员,您可以使用这两者中的任意一个来搜索文本。“替换”命令是“查找”命令的扩展。

使用 Selection 对象查找文本时,指定的所有搜索条件只适用于当前选择的文本。如果 Selection 是插入点,则搜索整个文档。如果找到匹配搜索条件的项,选择将自动更改以突出显示找到的项。

使用 Selection 对象查找文本

下面的过程搜索字符串“find me”。找到第一个后,它突出显示该词并显示一个消息框。
// C#
internal void SelectionFind()
{
string strFind = "find me";
Word.Find fnd = ThisApplication.Selection.Find;
fnd.ClearFormatting();
fnd.Text = strFind;
object missingValue = Type.Missing;

if (fnd.Execute(ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue))
{
MessageBox.Show("Text found.");
}
else
{
MessageBox.Show("The text could not be located.");
}
}

需要注意的是,Find 条件是累积的,这意味着一个条件会与前面的搜索条件累加起来。在搜索前可使用 .ClearFormatting() 方法清除上一次搜索的格式设置。

使用 Range 对象查找文本可以使您在用户界面不显示任何内容的情况下搜索文本。如果找到匹配搜索条件的文本,Find 方法将返回 True,否则返回 False。如果找到了文本,该方法还会重新定义 Range 对象以匹配搜索条件。

使用 Range 对象查找文本

定义一个由文档的第二段组成的 Range 对象。
// C# Word.Range rng = ThisDocument.Paragraphs[2].Range;
使用 Find 方法,首先清除任何现有的格式设置选项,然后搜索字符串“find me”。
// C#Word.Find fnd = rng.Find; fnd.ClearFormatting(); object missingValue = Type.Missing; object findStr = "find me"; if (fnd.Execute(
在消息框中显示搜索结果,最后选择 Range 以使其可见。
// C# { MessageBox.Show("Text found."); } else { MessageBox.Show("Text not found."); } rng.Select();
如果搜索失败,则第二段被选中;如果搜索成功,则显示搜索条件。

完整的方法如下所示:

// C#
internal void RangeFind()
{
Word.Range rng = ThisDocument.Paragraphs[2].Range;
Word.Find fnd = rng.Find;
fnd.ClearFormatting();
object missingValue = Type.Missing;
object findStr = "find me";
if (fnd.Execute(ref findStr, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue,
ref missingValue, ref missingValue, ref missingValue))
{
MessageBox.Show("Text found.");
}
else
{
MessageBox.Show("Text not found.");
}
rng.Select();
}

0 评论:

发表评论