1

我正在使用以下 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

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

4

3 回答 3

6

我让它工作了。感谢AnalystCave.com的帮助。这就是我所做的:

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

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事件。

于 2015-06-25T21:41:44.403 回答
1

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

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

于 2015-06-25T15:46:46.457 回答
1

使用 Word 2016,我发现有必要进行更改

Set X.App = Word.Application

应该

Set X.appWord = Word.Application
于 2016-11-18T09:20:41.477 回答