代码之家  ›  专栏  ›  技术社区  ›  Dark Daskin

如何在保存前在Word中运行宏?

  •  6
  • Dark Daskin  · 技术社区  · 12 年前

    如何使Microsoft Word在每次保存文档之前都运行VBA宏?是否可以在不向文档本身添加宏的情况下完成此操作?

    3 回复  |  直到 12 年前
        1
  •  15
  •   Dark Daskin    12 年前

    您可以在中订阅应用程序事件 Document_Open 通过使用 WithEvents 变量和常规方法名称( VariableName_EventName ). 也适用于模板。

    您可以将此代码放入 ThisDocument 对象,或创建一个单独的类模块,如所述 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
  •  2
  •   daghrb6    7 年前

    您必须在正确的位置添加代码位。

    这必须位于公共变量或常量分解中代码页的顶部

     Private WithEvents App As Word.Application 
    

    然后将其添加为打开文档事件。

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

    这是在保存命令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
    

    阅读有关打印输出方法的更多信息: Microsoft VBA - PrintOut

    阅读有关SaveAs2的更多信息: Microsoft VBA - SaveAs2

    阅读有关FileFormat for Saving的更多信息: Microsoft VBA - FileFormat for Saving

        3
  •  -1
  •   FelixSFD Tushar Panjwani    9 年前

    尝试将文件保存在 .xlsm ,然后关闭、打开并再次保存。它应该工作正常。