【问题标题】:Using VBA on word, how do I change fields on header?在 word 上使用 VBA,如何更改标题上的字段?
【发布时间】:2021-08-20 15:35:40
【问题描述】:

我正在制作一个可以复制到不同文件夹的模板文档。当我打开文档时,我希望它在同一文件夹中找到一个名为“Mod127*.xlsx”的 Excel 文件,并将所有字段的源路径更新为该 Excel 文件。

我为此效果编写了这段代码,它可以工作,但位于文档标题中的字段除外

Dim fieldCount As Integer, x As Long
With ActiveDocument
    ficheiro = Dir(.Path & "\Mod127*")
    If ficheiro = "" Then
        MsgBox "Model 127 not found in folder"
    Else
        fieldCount = .Fields.Count
        For x = 1 To fieldCount
            With .Fields(x)
                If .Type = 56 Then ' Type 56 is an excel link
                    .LinkFormat.SourceFullName = ActiveDocument.Path & "\" & ficheiro
                    .Update
                    .LinkFormat.AutoUpdate = False
                    DoEvents
                End If
            End With
        Next x
    End If
End With

知道如何访问该标题字段吗?

我还尝试将其中一个字段交叉引用到标题,但在代码运行后我得到一个“未找到引用”

【问题讨论】:

    标签: vba ms-word reference


    【解决方案1】:

    页眉和页脚是Section 的子对象。根据该部分的页面布局,最多可能有 3 个页眉和页脚,因此您需要知道要更新哪些页眉和页脚。下面的代码应该可以帮助您入门。

            With .Sections(1).Headers(wdHeaderFooterPrimary).Range.Fields(1)
                    .LinkFormat.SourceFullName = ActiveDocument.Path & "\" & ficheiro
                    .Update
                    .LinkFormat.AutoUpdate = False
                    DoEvents
            End With
    

    【讨论】:

    • 谢谢,这就是我所需要知道的,添加了另一个循环来遍历所有部分,现在一切都正确更新了
    猜你喜欢
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    相关资源
    最近更新 更多