6
votes

How to make Microsoft Word to run a VBA macro every time before any document is saved? Could it be done without adding macros into the document itself?

3

3 Answers

14
votes

You can subscribe to application events in Document_Open by using WithEvents variable and conventional method names (VariableName_EventName). Works in templates as well.

You can put this code into ThisDocument object, or make a separate class module as described here.

Private WithEvents App As Word.Application

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

Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
MsgBox("BeforeSave")
End Sub

List of all application events.

2
votes

You must add the code bits at the correct place.

This must be at the top of your code page amongst your public variables or constant declerations

 Private WithEvents App As Word.Application 

Then add this as an open document event.

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

This is the event that fires on save command Ctrl+s or save icon. I added my own save format and print as I saw It most useful in the case of people filling out forms and you don't want them to overwrite the initial template.

Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
''save file with the saveas2 command.
ActiveDocument.SaveAs2 FileName:="YourDocumentNameORVariable" + _
" Date_" + Format(Now(), "yy-mm-dd"), _
FileFormat:=wdFormatDocumentDefault, _
SaveFormsData:=True
''addition to print file upon save
ActiveDocument.PrintOut Background:=True, Range:=wdPrintAllDocument, Copies:=1, Collate:=True
End Sub

Read more about Printout methods: Microsoft VBA - PrintOut

Read more about SaveAs2: Microsoft VBA - SaveAs2

Read more about FileFormat for Saving: Microsoft VBA - FileFormat for Saving

-1
votes

try saving your file in .xlsm, then close, open and save it again. it should work fine.