简体   繁体   中英

Find and Replace footer text in Word with an Excel VBA Macro

I'm trying to make a macro in Excel which opens a Word document, find a especify text, which is inside of footer in word doc, and replace it for a text.

At the moment, my macro opens the word doc but I couldn't figure out how to get into footer and find those texts.

    Dim objWord
    Dim objDoc
    Set objWord = CreateObject("Word.Application")
    Set objDoc = objWord.Documents.Open(ThisWorkbook.Path & "/NotaPromissoriaAutomatica.docx")
    objWord.Visible = True

The footer have two texts which have to be replaced

1 - VAR_CIDADE > Which will be replaced the current city (which is in A1 of my excel table)
2 - VAR_DATA > Which will be replaced the current date (which is in A2 of my excel table)

I created a test document with a single page, header and footer, with the footer using the keyword "VAR_DATA". The example code below will search for all footers in the document and make the replacement. Notice that the code only searches in Section(1) though. If you have more sections, you may have to create an outer loop to search for each footer in every section.

Option Explicit

Public Sub FixMyFooter()
    Dim myWord As Object
    Dim myDoc As Word.Document
    Set myWord = CreateObject("Word.Application")
    Set myDoc = myWord.Documents.Open("C:\Temp\footertest.docx")

    Dim footr As Word.HeaderFooter
    For Each footr In myDoc.Sections(1).Footers
        With footr.Range.Find
            .Text = "VAR_DATA"
            .Replacement.Text = Format(Now(), "dd-mmm-yyyy")
            .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindStop
        End With
    Next footr

    myDoc.Save
    myWord.Quit
End Sub

You'll need to expand the example to find your additional text with your own formatting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM