Word VBA - DocumentBeforeSave 事件?

Word VBA - DocumentBeforeSave event?

我正在使用以下 VBA 代码在保存 Word 文档时显示一个消息框,

Public WithEvents appWord as Word.Application 

Private Sub appWord_DocumentBeforeSave _ 
 (ByVal Doc As Document, _ 
 SaveAsUI As Boolean, _ 
 Cancel As Boolean) 

 Dim intResponse As Integer 

 intResponse = MsgBox("Do you really want to " _ 
 & "save the document?", _ 
 vbYesNo) 

 If intResponse = vbNo Then Cancel = True 
End Sub

此代码是在 Class 中编写的。但这不起作用。保存时没有任何反应。这里有什么问题?

将它放在 Word 中 VBA 项目的 ThisDocument 部分,而不是 Class 中,因为它在那里不起作用。

这是一个例子: https://msdn.microsoft.com/en-us/library/office/ff838299.aspx

我成功了。感谢 AnalystCave.com 的帮助。这就是我所做的:

我创建了一个名为 EventClassModule 的新 class 并复制了以下代码,

Public WithEvents App As Word.Application

Private Sub App_DocumentBeforeSave _
 (ByVal Doc As Document, _
 SaveAsUI As Boolean, _
 Cancel As Boolean)

 Dim intResponse As Integer

 intResponse = MsgBox("Do you really want to " _
 & "save the document?", _
 vbYesNo)

 If intResponse = vbNo Then Cancel = True
End Sub

然后创建了一个名为mdlEventConnect的模块并复制了下面的代码,

Dim X As New EventClassModule

Sub Register_Event_Handler()
 Set X.App = Word.Application
End Sub

此后在ThisDocument上复制了以下代码,

Private Sub Document_New()
    Register_Event_Handler
End Sub

Private Sub Document_Open()
    Register_Event_Handler
End Sub

保存文档并重新打开。现在,当我尝试保存文档时,它完美地执行了 DocumentBeforeSave 事件。

对于 Word 2016,我发现有必要进行更改

Set X.App = Word.Application

应该是

Set X.appWord = Word.Application