首页 > 解决方案 > VBA代码替换页眉/页脚,而不仅仅是主体

问题描述

我找到并编写了一个代码,以便通过 Excel 表替换 Word 文档中的文本。但问题是代码仅适用于文本的主体,而不适用于文档的页眉/页脚。那么我在代码中使用了 StoryRange,代码如下,但它仍然给我的故事范围错误?如果我删除故事范围,那么替换仅适用于正文而不适用于页眉/页脚?关于我做错了什么以及如何解决这个问题的任何想法?

   Sub CompleteTask()

'Defining the dim
Dim ws As Worksheet
Dim wsh As Worksheet
Dim msWord As Object
Dim itm As Range
Dim myStoryRange As Object

Set ws = Sheets("Sheet1")
Set wsh = Sheets("Home")
Set msWord = CreateObject("Word.Application")

'Inserting the With Loop to open the Word Document
With msWord
    .Visible = True
    .Documents.Open (ThisWorkbook.Path & "/" & wsh.Range("B3").Value & ".docx")
    .Activate
    
    For Each myStoryRange In msWord.StoryRanges
        With myStoryRange.Find
        .ClearFormatting
        .Replacement.ClearFormatting
            For Each itm In ws.UsedRange.Columns("C").Cells
            .Text = itm.Value2
            .Replacement.Text = itm.Offset(, -1).Value2
            .MatchCase = False
            .MatchWholeWord = False
            .Execute Replace:=2
            Next
        End With
    Next myStoryRange
    
    'Saving the File into a new folder
    .ActiveDocument.SaveAs wsh.Range("B5").Value & "\" & wsh.Range("B4") & ".docx"
    .Quit
    'SaveChanges:=True

End With

End Sub

标签: excelvbareplacems-word

解决方案


推荐阅读