【问题标题】:VBA find and replace in a word doc's footerVBA在word文档的页脚中查找和替换
【发布时间】:2021-03-13 21:05:02
【问题描述】:

我有一个文档,其页脚中有一堆 <<system>>。 到目前为止,我只是将它们突出显示并粘贴过来,这非常乏味。 我希望 VBA 为我执行此操作。

我编写了一个宏来处理文档中的所有查找和替换,但它在页脚中不起作用。

在 google 上查找,似乎我发现的只是如何使用 word 中的 vba 来完成,但我需要在 excel 中使用 vba。有没有可能让它从那里工作?

使用的 vba(适用于 word doc 中的所有内容,除了页脚中的内容):

Dim objword
Set objword = GetObject(, "Word.Application")

With objword.ActiveDocument.Content
    With .Find
        .Execute FindText:="thing to search", ReplaceWith:="thing to replace", Replace:=1 '(or 2)
    End With
End With

【问题讨论】:

  • 第二个问题属于单独的帖子。这是一个问答网站 - 请注意,question 是单数,而不是复数。
  • 好的,第二个问题我去掉了,单独问。

标签: excel vba ms-word


【解决方案1】:

如果您在 Excel 中添加对 Word 对象的引用,生活会轻松很多,否则,这可能在 Excel 中起作用:

Public Sub UpdateWord()

Dim wrdObj As Object    ' Application object
Dim wrdDoc As Object    ' Word object
Dim sect As Object      ' Section
Dim footr As Object     ' Footer
Dim sel As Object       ' Selection

Dim kwrd_find As String: kwrd_find = "<<system>>" ''' Keyword to find
Dim kwrd_replace As String: kwrd_replace = "Hello" ''' Word to replace keyword

Dim DocPath As String: DocPath = "C:\path\to\my\word-document.docx"

Set wrdObj = GetObject(, "Word.Application")

''' Open word document
''' Change `Visible` to False if you don't want to see it.
Set wrdDoc = wrdObj.Documents.Open(DocPath, ReadOnly:=False, Visible:=True)

On Error Resume Next

With wrdDoc
    ''' Run through all sections and footers (you can add headers, too).
    For Each sect In .Sections
        For Each footr In sect.Footers
            With footr.Range.Find
                .Text = kwrd_find                ''' Keyword to find
                .Replacement.Text = kwrd_replace ''' Word to replace keyword
                .Wrap = wdFindContinue ''' Wrap it up.
                Call .Execute(Replace:=wdReplaceAll)
            End With
        Next
    Next sect
End With

''' Close and save document
Call wrdDoc.Close(SaveChanges:=True)

''' Clean up e'rything.
Set wrdDoc = Nothing
Set wrdObj = Nothing


End Sub

【讨论】:

  • 效果很好,谢谢!唯一的事情是之后它使单词 doc 的视图变得奇怪,我必须单击视图下的“打印布局”才能将其恢复正常。您知道自动执行此操作的 VBA 代码是什么吗?我很难找到那个。请注意,我省略了关闭 word doc 的代码,因为我想让它保持打开状态。
  • 当然可以。在 .Close() 方法上,还有几个其他选项。一种是 OriginalFormat,它可以采用三个选项之一。你可以试试wrdDoc.Close(SaveChages:=True, OriginalFormat:=wdOriginalDocumentFormat)。保存()参考:docs.microsoft.com/en-us/office/vba/api/…。格式化枚举:docs.microsoft.com/en-us/office/vba/api/word.wdoriginalformat
  • @workinonvba - 由于代码正在选择页脚,因此视图已更改,这是完全没有必要的。删除For Each footr In sect.Footers后面的两行代码,将With sel.Find改为With footr.Range.Find
  • @TimothyRylatt 感谢您的提醒!我承认我以前没有使用过这种代码,所以我非常感谢这些建议。 OP 还需要指定保存格式吗?
  • “OP 还需要指定保存格式吗?” - 不。 OriginalFormat指的是SaveFormat,即docx、docm、dotx、dotm等,对视图类型没有影响。
猜你喜欢
  • 1970-01-01
  • 2019-05-20
  • 2016-01-26
  • 2017-08-06
  • 2021-10-13
  • 2018-11-11
  • 2019-08-27
  • 1970-01-01
  • 2012-03-08
相关资源
最近更新 更多