Word VBA教程:查找并替换文字或格式

通过Find 和Replacement对象可实现查找和替换功能。Selection 和Range对象可以使用 Find对象。从 Selection 或 Range对象访问 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

 

猜你喜欢

转载自blog.csdn.net/ls13552912394/article/details/81806542