Word VBA - DocumentBeforeSave event?

人走茶凉 提交于 2019-11-29 12:58:35
Codename K

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.

Put it in the ThisDocument section of your VBA Project in Word, not in a Class as it won't work there.

Here is an example: https://msdn.microsoft.com/en-us/library/office/ff838299.aspx

freeflow

With Word 2016 I found that a change was necessary

Set X.App = Word.Application

should be

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