How to run a macro in Word before save?

痴心易碎 提交于 2019-12-29 07:07:06

问题


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?


回答1:


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:


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




回答3:


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



来源:https://stackoverflow.com/questions/24702493/how-to-run-a-macro-in-word-before-save

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