vbams-wordsavefiledialogbefore-save

Word VBA - DocumentBeforeSave event?


I am using the following VBA code to make a message box appear while saving the Word document,

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

This code was written in a Class. But this does not work. Nothing happens when saving. What is the issue here?


Solution

  • I made it to work. Thanks to AnalystCave.com for the help. This is what I did:

    I create a new class named EventClassModule and copied the following code,

    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
    

    Then created a module named mdlEventConnect and copied the following code,

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

    After this on the ThisDocument copied the following code,

    Private Sub Document_New()
        Register_Event_Handler
    End Sub
    
    Private Sub Document_Open()
        Register_Event_Handler
    End Sub
    

    Saved the document and re-opened it. Now when I try to save the document it executed the DocumentBeforeSave event perfectly.