PDA

View Full Version : [SOLVED:] VBA Coding: Event register handler for this document only



Olaf
10-01-2020, 05:55 AM
Hi,

I have a document which needs to do a couple of actions before it is saved.
I have a Macro for that. It works fine, the only issue is, that it is also triggered in all other open documents and that is not what I want.
It only needs to be triggered in the document itself.

The code I am using:

Microsoft Word Objects:
ThisDocument:



Private Sub Document_New()

Register_Event_Handler

End Sub




Private Sub Document_Open()

Register_Event_Handler

End Sub


Module:


mdlEventConnect

Dim X As New EventClassModule




Sub Register_Event_Handler()

Set X.App = Word.Application

End Sub

Class Modules:

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

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


If intResponse = vbNo Then Cancel = True

End Sub



Attached a word document with my code.

Does anybody know how that can be achieved?

Thanks in advance
Olaf

Paul_Hossler
10-01-2020, 06:25 AM
Try this

I tweaked the macros a little so I could trace things



Option Explicit


Public WithEvents App As Word.Application


Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
Dim intResponse As Integer

If ActiveDocument Is ThisDocument Then
'Do you want to save question?
If MsgBox("Do you R-E-E-E-ALLY want to save the document?", vbYesNo) = vbNo Then Cancel = True
End If

End Sub

Olaf
10-01-2020, 06:45 AM
It works now.
So simple, but it didn't cross my mind.

Many Thanks Paul.

Paul_Hossler
10-01-2020, 12:18 PM
Good thing I've got a simple mind :rotlaugh: