App_DocumentBeforeClose vba word

时间:2017-03-26 09:35:01

标签: vba word-vba

我想创建App_DocumentBeforeClose。

我使用了这段代码:

在ThisDocument中:

Private Sub Document_Open()
start
End Sub

在Modul中

Sub start()
Dim X As New EventClassModule
Set X.App = Word.Application
End Sub

在Mudel班:

 Public WithEvents App As Word.Application

 Private Sub App_DocumentBeforeClose(ByVal Doc As Document, Cancel As
 Boolean)
 MsgBox "App_DocumentBeforeClose"
 End Sub

当我关闭文档时,它没有显示MsgBox,为什么?

谢谢,

塔尔

1 个答案:

答案 0 :(得分:0)

你的sub正确运行但是X被实例化为 procedure 范围的变量,这样一旦start()结束,X超出范围并且不可用任何后续的DocumentBeforeClose()事件触发

您必须将X声明为Public变量

Public X As New EventClassModule  '<--| this way 'X' is "seen" throughout the entire life of the document


Sub start()
'    Dim X As New EventClassModule '<--| this way 'X' would be "seen" only at the moment 'start()' is running
    Set X.App = Word.Application
End Sub