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

那年仲夏 提交于 2021-01-27 12:12:23

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/55536409/find-and-replace-footer-text-in-word-with-an-excel-vba-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!