更新 Word 文件打开时的页眉、页脚和正文字段。

huangapple go评论71阅读模式
英文:

Updating fields in headers, footers, and main story in Word on file open

问题

我使用了该网站上的代码,它们都可以正常运行,只需手动运行。以下是代码示例。

为什么我打开文档时这个不能自动运行?

Private Sub Document_AutoOpen()
    UpdateAllFields
End Sub

Sub UpdateAllFields()
    Dim rng As Range
    Dim sec As Section
    Dim hdrFtr As HeaderFooter
    
    ' 更新正文中的域
    For Each rng In ActiveDocument.StoryRanges
        UpdateFieldsInRange rng
        Do While Not (rng.NextStoryRange Is Nothing)
            Set rng = rng.NextStoryRange
            UpdateFieldsInRange rng
        Loop
    Next rng
    
    ' 更新页眉和页脚中的域
    For Each sec In ActiveDocument.Sections
        For Each hdrFtr In sec.Headers
            UpdateFieldsInRange hdrFtr.Range
        Next hdrFtr
        
        For Each hdrFtr In sec.Footers
            UpdateFieldsInRange hdrFtr.Range
        Next hdrFtr
    Next sec
End Sub

Sub UpdateFieldsInRange(rng As Range)
    Dim fld As Field
    
    For Each fld In rng.Fields
        fld.Update
    Next fld
End Sub
英文:

I used code from questions on this site that all worked, just had to manually run them. Below is a code example.

Why isn't this working automatically when I open the document?

Private Sub Document_AutoOpen()
    UpdateAllFields
End Sub

Sub UpdateAllFields()
    Dim rng As Range
    Dim sec As Section
    Dim hdrFtr As HeaderFooter
    
    ' Update fields in the body
    For Each rng In ActiveDocument.StoryRanges
        UpdateFieldsInRange rng
        Do While Not (rng.NextStoryRange Is Nothing)
            Set rng = rng.NextStoryRange
            UpdateFieldsInRange rng
        Loop
    Next rng
    
    ' Update fields in headers and footers
    For Each sec In ActiveDocument.Sections
        For Each hdrFtr In sec.Headers
            UpdateFieldsInRange hdrFtr.Range
        Next hdrFtr
        
        For Each hdrFtr In sec.Footers
            UpdateFieldsInRange hdrFtr.Range
        Next hdrFtr
    Next sec
End Sub

Sub UpdateFieldsInRange(rng As Range)
    Dim fld As Field
    
    For Each fld In rng.Fields
        fld.Update
    Next fld
End Sub

答案1

得分: 2

Wherever you got Document_AutoOpen from, it's wrong. You either need a routine named AutoOpen in a standard module, or, in the ThisDocument module, you have an event handler named Document_Open.

英文:

Wherever you got Document_AutoOpen from, it's wrong. You either need a routine named AutoOpen in a standard module, or, in the ThisDocument module, you have an event handler named Document_Open.

更新 Word 文件打开时的页眉、页脚和正文字段。

huangapple
  • 本文由 发表于 2023年5月25日 23:03:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76333779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定