我想在单词页眉和页脚中搜索特定单词,然后用数据库中的单词替换它们。
目前,我可以在Word文档中除页眉和页脚以外的任何位置搜索和替换单词。
有人可以帮我解决这个问题吗?
普通搜索代码(有效):
Procedure FindAndReplace(Find,Replace:String);
Begin
//Initialize parameters
WrdApp.Selection.Find.ClearFormatting;
WrdApp.Selection.Find.Text := Find;
WrdApp.Selection.Find.Replacement.Text := Replace;
WrdApp.Selection.Find.Forward := True;
WrdApp.Selection.Find.Wrap := wdFindContinue;
WrdApp.Selection.Find.Format := False;
WrdApp.Selection.Find.MatchCase := False;
WrdApp.Selection.Find.MatchWholeWord := wrfMatchCase in Flags;
WrdApp.Selection.Find.MatchWildcards :=wrfMatchWildcards in Flags;
WrdApp.Selection.Find.MatchSoundsLike := False;
WrdApp.Selection.Find.MatchAllWordForms := False;
{ Perform the search}
if wrfReplaceAll in Flags then
WrdApp.Selection.Find.Execute(Replace := wdReplaceAll)
else
WrdApp.Selection.Find.Execute(Replace := wdReplaceOne);
End;
页眉和页脚搜索代码(不起作用):
WrdApp.Selection.Find.ClearFormatting;
WrdApp.Selection.Find.Text := 'Class';
WrdApp.Selection.Find.Replacement.Text := grade;
WrdApp.Selection.Find.Forward := True;
WrdApp.Selection.Find.Wrap := wdFindContinue;
WrdApp.Selection.Find.Format := False;
WrdApp.Selection.Find.MatchCase := False;
WrdApp.Selection.Find.MatchWholeWord := wrfMatchCase in Flags;
WrdApp.Selection.Find.MatchWildcards :=wrfMatchWildcards in Flags;
WrdApp.Selection.Find.MatchSoundsLike := False;
WrdApp.Selection.Find.MatchAllWordForms := False;
{ Perform the search}
if wrfReplaceAll in Flags then
WrdApp.ActiveDocument.Sections.Item(1).Headers.Item(wdHeaderFooterPrimary).Range.Find.Execute(Replace := wdReplaceAll)
else
WrdApp.ActiveDocument.Sections.Item(1).Headers.Item(wdHeaderFooterPrimary).Range.Find.Execute(Replace := wdReplaceOne);
它不起作用,因为您正在设置所选内容的"查找"对象,然后使用标题"范围的查找"对象。这些是不同的东西。
如果修改这些行
WrdApp.ActiveDocument.Sections.Item(1).Headers.Item(wdHeaderFooterPrimary).Range.Find.Execute(Replace := wdReplaceAll);
类似于以下内容(您需要正确使用德尔菲语法)
WrdApp.ActiveDocument.Sections.Item(1).Headers.Item(wdHeaderFooterPrimary).Range.Select;
WrdApp.Selection.Find.Execute(Replace := wdReplaceAll);
您应该看到改进,但我的猜测是(a)如果您可以避免使用Selection对象,则最好这样做,并且(b)如果您需要处理具有不同页眉和页脚的更一般的情况,事情可能会变得更加复杂。所以我建议你去
Word MVP 网站上的"使用宏替换文档中出现的文本",并研究他们拥有的代码。从VBA->Delphi翻译应该很容易。
我找到了答案,我只需要添加这一行即可将焦点设置为标题:
WrdApp.ActiveWindow.ActivePane.View.SeekView := wdSeekCurrentPageHeader;
,然后再次运行搜索命令。
谢谢你们。