英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论