簡體   English   中英

VBA 在word文檔的頁腳中查找和替換

[英]VBA find and replace in a word doc's footer

我有一個在其頁腳中有一堆<<system>>的文檔。 到目前為止,我只是將它們突出顯示並粘貼過來,這非常乏味。 我希望 VBA 為我做這件事。

我編寫了一個宏來處理文檔中的所有查找和替換,但它在頁腳中不起作用。

在谷歌上看,似乎我發現的只是如何使用 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

如果您在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM