How to run a macro in Word before save?

前端 未结 3 886
生来不讨喜
生来不讨喜 2020-12-18 10:08

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条回答
  • 2020-12-18 10:29

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

    0 讨论(0)
  • 2020-12-18 10:36

    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.

    0 讨论(0)
  • 2020-12-18 10:37

    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

    0 讨论(0)
提交回复
热议问题