Find/replace Word 文档页脚中的文本使用 Excel VBA

Find/replace texts in Word document footer using Excel VBA

我想替换 Word 文档中的一些标签。我当前的解决方案没有在文档页脚处实现 replacement/search。

我使用的 word 模板有 2 个不同的页脚(第一页与第二页的页脚不同)。我想在第二页的页脚中更改一些内容。

'replacement regarding CHAPTER 1
For CurRow = Tabelle2.Range("C2") To Tabelle2.Range("C3")
    If Tabelle2.Range("B" & CurRow).Value = "x" Then
        ReplacementTextF = "<<TagToBeFound>>"
        ReplacementText = "I am a customer"
        dataObjectLongText.SetText ReplacementText
        dataObjectLongText.PutInClipboard       'Copy to clipboard
        With WordDoc.Content.Find
            .Execute FindText:=ReplacementTextF, ReplaceWith:="^c", Replace:=2, Wrap:=wdFindContinue    'Paste from clipboard
        End With

到这里为止,一切正常。它找到所有文本并使用剪贴板替换它们(因为替换文本通常大于 255 个字符)。

为了查看页脚,我在上面的代码之后尝试了这个:

        With WordDoc.Sections(1).Footers(1).Range.Find
            .Execute FindText:=ReplacementTextF, ReplaceWith:="^c", Replace:=2, Wrap:=wdFindContinue    'Paste from clipboard
        End With

我尝试了几种解决方案。这是我最后的方法。我引用了Word对象库。

看来您正在使用后期绑定,您不能简单地使用 wdFindContinue 之类的 Word 常量;您需要声明它或使用它的等效数字。如果之前的 Find/Replace 使用通配符 and/or 格式化查找或替换参数,可能会出现其他问题,因此重置这些是明智的。尝试:

With WordDoc.Sections(1).Footers(1).Range.Find '1 = wdHeaderFooterPrimary
  .ClearFormatting
  .Replacement.ClearFormatting
  .Text = ReplacementTextF
  .Replacement.Text = "^c"    'Paste from clipboard
  .Wrap = 1 'wdFindContinue
  .MatchWildcards = False
  .Execute Replace:=2 'wdReplaceAll
End With

或:

With ActiveDocument.StoryRanges(9).Find '9 = wdPrimaryFooterStory
  .ClearFormatting
  .Replacement.ClearFormatting
  .Text = ReplacementTextF
  .Replacement.Text = "^c"    'Paste from clipboard
  .MatchWildcards = False
  .Wrap = 1 'wdFindContinue
  .Execute Replace:=2 'wdReplaceAll
End With

无论如何,由于页脚显示的内容与您在文档正文中替换 ReplacementTextF 的内容相同,因此您最好为 ReplacementTextF 分配一个唯一的样式名称,然后引用它通过页脚中的 STYLEREF 字段设置样式。在模板中执行此操作。这样,您就不需要在页脚中使用 Find/Replace。