Excel VBA:如何创建全局事件Global_beforsave()

时间:2013-10-16 16:02:29

标签: excel vba events excel-vba

我需要检测每个文件(* .xls,* .xlsx,* .xlsb,...)在保存之前在excel许多属性中打开。

在* .xlsm文件中我在此工作簿中包含Workbook_BeforeSave(),但仅对此工作簿可用。

我希望在* .xlam文件中包含一个全局事件,但我不知道该怎么做。

2 个答案:

答案 0 :(得分:2)

如Charles链接所示,您必须使用类模块来捕获来自其他对象的事件。

我的建议是重用ThisWorkbook对象:

'App variable which should be assigned to current Application instance:
Public WithEvents App As Excel.Application

'Use open event on your workbook to assign App
Private Sub Workbook_Open()
    Set App = Application
End Sub

'Code catching WorkbookBeforeSave event on App
Private Sub App_WorkbookBeforeSave(ByVal Wb As Workbook, ByVal SaveAsUI As Boolean, Cancel As Boolean)
    Debug.Print "Workbook "; Wb.Name; " is about to be saved..."
End Sub

答案 1 :(得分:1)

参见Chip Pearson关于Application Events的文章 here