DocumentBeforeClose syntax

可紊 提交于 2019-12-24 11:14:33

问题


I really don't know the syntax of the DocumentBeforeClose event. Following this page, I should create a class module called 'EventClassModule' (see also this article). So I did. Then I copied this piece of code (from the example of the first link) into that (class)module:

Public WithEvents appWord as Word.Application 

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

    Dim intResponse As Integer 

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

    If intResponse = vbNo Then Cancel = True 
End Sub

And finally I put this in a normal module, and executed it:

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

What does the 'X' means in this case, and what am I doing wrong? There is no event executed when I close the document now.


回答1:


X is an instance of the class you created (EventClassModule)

Your problem is that .App is not a property of EventClassModule. Change

Set X.App = Word.Application 

to the property you defined in your class

Set X.appWord = Word.Application 



回答2:


I tried the same thing! Actually it works for me. I have this in a class module named EventClassModule

Public WithEvents appWord As Word.Application

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

'Here is the code you want to do before it close
MsgBox "WORKING!"

End Sub

And in a module (not a class module) I have this

Dim X As New EventClassModule

Sub AutoExec()

    'Call any other sub or function you want

    Call Register_Event_Handler

End Sub

Sub Register_Event_Handler()

    Set X.appWord = Word.Application

End Sub

AutoExec is called as soon as the document is loaded. So it calls the sub Register_Event_Handler to register the object X (which is a object EventClassModule, the class module created). So X will be annonced that the document is about to close

hope it helps!



来源:https://stackoverflow.com/questions/8693798/documentbeforeclose-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!