vba 如何在保存前在 Word 中运行宏?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24702493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run a macro in Word before save?
提问by Dark Daskin
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?
在保存任何文档之前,如何让 Microsoft Word 每次都运行 VBA 宏?可以在不向文档本身添加宏的情况下完成吗?
回答by Dark Daskin
You can subscribe to application events in Document_Open
by using WithEvents
variable and conventional method names (VariableName_EventName
). Works in templates as well.
您可以Document_Open
使用WithEvents
变量名和常规方法名 ( VariableName_EventName
)订阅应用程序事件。也适用于模板。
You can put this code into ThisDocument
object, or make a separate class module as described here.
您可以将此代码放入ThisDocument
对象中,或按照此处所述制作单独的类模块。
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
回答by Damien Vallery-Radot
try saving your file in .xlsm
, then close, open and save it again. it should work fine.
尝试将文件保存在 中.xlsm
,然后关闭、打开并再次保存。它应该可以正常工作。
回答by daghrb6
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.
这是在保存命令 Ctrl+s 或保存图标上触发的事件。我添加了我自己的保存格式和打印,因为我看到它在人们填写表格并且您不希望他们覆盖初始模板的情况下最有用。
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
阅读有关打印输出方法的更多信息:Microsoft VBA - PrintOut
Read more about SaveAs2: Microsoft VBA - SaveAs2
阅读有关 SaveAs2 的更多信息:Microsoft VBA - SaveAs2
Read more about FileFormat for Saving: Microsoft VBA - FileFormat for Saving
阅读有关用于保存的文件格式的更多信息:Microsoft VBA - 用于保存的文件格式