【问题标题】:Find and replace in first page footer in Word document在 Word 文档的第一页页脚中查找和替换
【发布时间】:2016-01-26 03:10:00
【问题描述】:

我使用这个宏来替换不同word文档中的一些值,但它不会替换第一页页脚中的文本。我想这是因为首页页脚与其他页脚不同。我刚开始使用 VBA 代码,所以我不知道如何解决这个问题。如果有人可以为我修改宏,以便它也可以在第一页的页脚中查找和替换值,我将不胜感激?

Sub DoReplace()

Const Find1 = "FIND TEXT"
Const Replace1 = "REPLACE TEXT"

Const Find2 = "FIND TEXT"
Const Replace2 = "REPLACE TEXT"

Dim FilePick As FileDialog
Dim FileSelected As FileDialogSelectedItems
Dim WordFile As Variant  ' FileName placeholder in selected files loop
Dim FileJob As String    ' Filename for processing

Dim WorkDoc As Object
Dim WholeDoc As Range
Dim FooterDoc As Range

On Error GoTo DoReplace_Error

    Set FilePick = Application.FileDialog(msoFileDialogFilePicker)

    With FilePick
        .Title = "Choose Report Template"
        .Filters.Clear
        .Filters.Add "Word Documents & Templates", "*.do*"
        .Filters.Add "Word 2003 Document", "*.doc"
        .Filters.Add "Word 2003 Template", "*.dot"
        .Filters.Add "Word 2007 Document", "*.docx"
        .Filters.Add "Word 2007 Template", "*.dotx"
        .Show
    End With

    Set FileSelected = FilePick.SelectedItems

    If FileSelected.Count <> 0 Then

        For Each WordFile In FileSelected

            FileJob = WordFile

            Set WorkDoc = Application.Documents.Open(FileJob, , , , , , , , , , , False)

            Set WholeDoc = WorkDoc.Content
            Set FooterDoc = WorkDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range

            With FooterDoc
                .Find.Execute Find1, True, True, , , , True, , , Replace1, wdReplaceAll
                .Find.Execute Find2, True, True, , , , True, , , Replace2, wdReplaceAll
            End With

            With WholeDoc.Find
                .Execute Find1, True, True, , , , True, , , Replace1, wdReplaceAll
                .Execute Find2, True, True, , , , True, , , Replace2, wdReplaceAll

            End With

            WorkDoc.Save
            WorkDoc.Close

        Next

    End If

    MsgBox "Completed"

DoReplace_Exit:

    Set WholeDoc = Nothing
    Set FilePick = Nothing

    Set WorkDoc = Nothing
    Set FooterDoc = Nothing

    Exit Sub

DoReplace_Error:

    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure DoReplace of VBA Document ReplaceMulti"
    Resume DoReplace_Exit

End Sub

【问题讨论】:

    标签: vba replace ms-word footer


    【解决方案1】:

    创建另一个变量并将另一个页脚分配给它。类似的东西

    Dim footerPage1 as Word.Range
    Set footerPage1 = WorkDoc.Sections(1).Footers(wdHeaderFooterFirstPage).Range
    

    但是有一种更好的方法可以在整个文档中进行搜索,而无需了解和指定每个“故事”。首先查找有关属性的文档:StoryRanges

    这包含可以让您开始的示例代码。然后在互联网上搜索以下术语,详细了解如何使用它:

    Word find StoryRanges
    

    【讨论】:

    • 非常感谢您的帮助!!!效果很好!我会调查你的建议。再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 2019-05-20
    • 2019-12-03
    • 2019-08-27
    • 1970-01-01
    • 2015-07-09
    • 2012-06-26
    • 2017-08-06
    相关资源
    最近更新 更多