R – Call UserForm on Save

ms-wordvba

How do I go about calling a userform in VBA when user clicks on the Save button in MS Word?

Best Answer

You have two options to do that: You can either override the built-in FileSave and FileSaveAs commands, or you can create an event handler for the application's DocumentBeforeSave event (which is a little more work to do).

Overriding the built-in commands can be accomplished by adding the following code to a VBA module (adjust the type of the user form to be displayed accordingly):

' override File -> Save
Public Sub FileSave()

    CustomSave
    ' call ActiveDocument.Save to actually save the document

End Sub

' override File -> Save As...
Public Sub FileSaveAs()

    CustomSave
    ' call ActiveDocument.SaveAs to actually save the document

End Sub

Sub CustomSave()

    Dim frm As New frmCustomSave
    frm.Show

End Sub

The second option can be implemented by placing the following code under Microsoft Word Objects -> ThisDocument in the VBA editor:

Option Explicit

Private WithEvents wdApp As Word.Application

Private Sub Document_New()
    Set wdApp = Word.Application
End Sub

Private Sub Document_Open()
    Set wdApp = Word.Application
End Sub

Private Sub wdApp_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)

    Dim frm As New frmCustomSave
    frm.Show

End Sub
Related Topic