在Excel中使用Excel VBA宏查找和替换页脚文本 [英] Find and Replace footer text in Word with an Excel VBA Macro

查看:141
本文介绍了在Excel中使用Excel VBA宏查找和替换页脚文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Excel 中制作一个,该宏会打开 Word 文档,找到一个具体的文本,该文本位于 footer ,然后将其替换为文本.

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.

此刻,我的宏打开了doc一词,但我不知道如何进入页脚并找到这些文本.

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>将替换为当前城市(位于我的excel表的A1中)
2-VAR_DATA>它将被替换为当前日期(在我的Excel表的A2中)

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)

推荐答案

我创建了一个包含单页,页眉和页脚的测试文档,页脚使用关键字"VAR_DATA".下面的示例代码将搜索文档中的所有页脚并进行替换.请注意,代码会在 Section(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.

这篇关于在Excel中使用Excel VBA宏查找和替换页脚文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆