通过Find 和Replacement对象可实现查找和替换功能。Selection 和Range对象可以使⽤ Find对象。从 Selection 或 Range对象访问 Find对象时,查找操作会略有不同。
查找并选定⽂字
如果从 Selection对象访问 Find对象,当找到搜索条件时,就会更改所选内容。下列⽰例选定下⼀个出现的“Hello”。如果到达⽂档结尾时仍未找到“Hello”,则停⽌搜索。
With Selection.Find .Forward = True
.Wrap = wdFindStop .Text = \"Hello\" .ExecuteEnd 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 = TrueEnd With
下列⽰例使⽤ Execute⽅法的参数,执⾏结果与上例相同。
Set myRange = ActiveDocument.Content
myRange.Find.Execute FindText:=\"blue\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:=wdFindContinueEnd 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:=\"\ Format:=True, Replace:=wdReplaceAllEnd With
因篇幅问题不能全部显示,请点此查看更多更全内容