我是VBA的新手,我正在尝试编写一个宏,在用户保存文档之前执行字段更新。我的第一次尝试是拦截这样的Save
命令:
Sub FileSave()
'
' FileSave Macro
' Saves the active document or template, and updates fields
'
Fields.Update
ActiveDocument.Save
End Sub
但有一位导游建议不要这样做,而是使用DocumentBeforeSave()
,所以这是我的新尝试:
Private Sub oApp_DocumentBeforeSave(ByVal Doc As Document, _
SaveAsUI As Boolean, Cancel As Boolean)
Fields.Update
End Sub
第一个例子给出了以下错误:
“运行时错误'424':需要对象”
第二个示例不更新字段。我已经尝试了ThisDocument
对象中的第二个代码,并作为一个新的模块类。然而,当我保存时,字段仍然没有更新。在旁注中,他们可以使用它。
Private Sub Document_Close()
Fields.Update
Save
End Sub
这似乎是一项简单的任务,但似乎没有用。
答案 0 :(得分:1)
在ThisDocument
代码模块中,使用Application
关键字添加WithEvents
对象,以便您可以回复其事件:
Dim WithEvents TheApp As Word.Application
为Document_Open()
添加一个事件处理程序,将您的变量分配给活动的Application
对象:
Private Sub Document_Open()
Set TheApp = ThisDocument.Application
End Sub
为Application_DocumentBeforeSave()
添加事件处理程序。在此活动中,使用传递给它的Doc
对象来更新您的文档:
Private Sub TheApp_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
Doc.Fields.Update
End Sub
将您的文档另存为"Macro-Enabled Document (*.docm)"
。
关闭文档并重新打开。
那应该是它。如果要确保代码正常工作,请在MsgBox()
语句之前添加断点或Doc.Fields.Update
,以确保调用事件处理程序并在更新之前和之后检查您的值。 / p>