本文介绍了一个使用Visual Basic for Applications (VBA) 在Word中创建的自动化脚本,包括如何设置WithEvents属性、事件处理(如窗口选择变化时调用`myUpDate`函数)、以及如何在文档打开时管理和更新字段。重点在于事件驱动的文档操作和字段更新的高效管理。
Option Explicit
Private WithEvents WdApp As Word.Application
'以上声明为 Word对象 必须加关键字 WithEvents 这是前提1
'事件代码必须在ThisDocument中,这是前提2
Dim aStory As Range
Sub myUpDate()
Application.ScreenUpdating = False
For Each aStory In ActiveDocument.StoryRanges
aStory.Fields.Update
Next aStory
Application.ScreenUpdating = True
' Runtimer
End Sub
Private Sub Document_open()
Set WdApp = Word.Application '文档打开时 WdApp取得整个Word对象
With ActiveWindow.View
.ShowRevisionsAndComments = False
.RevisionsView = wdRevisionsViewFinal
End With
Selection.WholeStory
Selection.Fields.Update
Selection.MoveLeft Unit:=wdCharacter, Count:=1
End Sub
Private Sub WdApp_WindowSelectionChange _
(ByVal Sel As Selection)
myUpDate
End Sub