查找并替换文字或格式

   

通过 FindReplacement 对象可实现查找和替换功能。SelectionRange 对象可以使用 Find 对象。从 SelectionRange 对象访问 Find 对象时,查找操作会略有不同。

查找并选定文字

如果从 Selection 对象访问 Find 对象,当找到搜索条件时,就会更改所选内容。下列示例选定下一个出现的“Hello”。如果到达文档结尾时仍未找到“Hello”,则停止搜索。

With Selection.Find
    .Forward = True
    .Wrap = wdFindStop
    .Text = "Hello"
    .Execute
End With

Find 对象包含与“查找和替换”对话框中的选项相关的属性(在“编辑”菜单上选择“查找”可显示该对话框)。可以设置 Find 对象单独的属性或使用 Execute 方法的参数,如下例所示。

Selection.Find.Execute FindText:="Hello", _
    Forward:=True, Wrap:=wdFindStop

查找文字,但不更改所选内容

如果从 Range 对象访问 Find 对象,则找到搜索条件时,不更改所选内容,但是会重新定义 Range 对象。下列示例在活动文档中查找第一个出现的“blue”。如果找到该单词,则重新定义该区域,并将加粗格式应用于单词“blue”。

With ActiveDocument.Content.Find
    .Text = "blue"
    .Forward = True
    .Execute
    If .Found = True Then .Parent.Bold = True
End With

下列示例使用 Execute 方法的参数,执行结果与上例相同。

Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:="blue", Forward:=True
If myRange.Find.Found = True Then myRange.Bold = True

使用 Replacement 对象

Replacement 对象代表查找和替换操作的替换条件。Replacement 对象的属性和方法对应于“查找和替换”对话框中的选项(单击“编辑”菜单中的“查找”或“替换”命令可显示该对话框)。

可通过 Find 对象使用 Replacement 对象。下列示例将所有单词“hi”替换为“hello”。由于 Find 对象是通过 Selection 对象访问的,所以当找到搜索条件时,会更改所选内容。

With Selection.Find
    .ClearFormatting
    .Text = "hi"
    .Replacement.ClearFormatting
    .Replacement.Text = "hello"
    .Execute Replace:=wdReplaceAll, Forward:=True, _
        Wrap:=wdFindContinue
End With

下列示例取消活动文档中的加粗格式。Find 对象的 Bold 属性为 True,而 Replacement 对象的该属性为 False。若要查找并替换格式,可将查找和替换文字设为空字符串 (""),并将 Execute 方法的 Format 参数设为 True。由于从 Range 对象访问 Find 对象,所选内容将保持不变(Content 属性返回一个 Range 对象)。

With ActiveDocument.Content.Find
    .ClearFormatting
    .Font.Bold = True
    With .Replacement
        .ClearFormatting
        .Font.Bold = False
    End With
    .Execute FindText:="", ReplaceWith:="", _
        Format:=True, Replace:=wdReplaceAll
End With