Workbook_Before跨应用程序closures
我在我的插件的“ This Workbook
”中有Workbook_BeforeClose
,并且当我在同一个Excel实例中打开几个工作簿并尝试closures它们中的每一个时, Workbook_BeforeClose
不会为每个在实例中打开的这样的工作簿而被调用, workbbook。
有没有办法让Workbook_BeforeClose
调用excel实例中的所有工作簿,我需要在每个工作簿closures时执行任务?
有几个步骤要遵循。
-
在Excel IDE / VBA环境中创build类模块。 在一本将保持开放直到结束的工作簿中进行。
-
将类模块名称更改为
AppClass
-
把这个代码放在
AppClass module
里面:Public WithEvents EXL As Application Private Sub EXL_WorkbookBeforeClose(ByVal Wb As Workbook, Cancel As Boolean) 'sample msgbox MsgBox "You are about to close Workbook: " & Wb.Name 'here your code End Sub
-
在任何标准模块中,如
Module1
,插入以下代码:Public appEXL As New AppClass Sub Required_Initialization() 'run it once or run it when this workbook is opened Set appEXL.EXL = Application End Sub
-
运行第4步中创build的子
-
做一些testing:a)创build新的空工作簿,然后尝试closures它。 您将得到MsgBox调用您即将closures的工作簿的名称。
-
根据需要进行调整。
重要! 类是VBA编程中比较困难的部分。 为了更好地理解,请尝试在networking中search任何其他信息。
KazJaw的回答是一个好主意。
我有一个应用程序范围的插件使用他所概述的技术,其中包含以下代码:
Private Sub xlApp_WorkbookOpen(ByVal Wb As Excel.Workbook) On Error GoTo NoBookOpen: If Application.Calculation = xlCalculationManual And LCase(Left(ActiveWorkbook.Name, 6)) <> "export" Then If MsgBox("Calculation is set to Manual!" & vbCrLf & _ "It will now be put back to Automatic", vbYesNo, "CALCULATION") = vbYes Then Application.Calculation = xlCalculationAutomatic End If End If NoBookOpen: End Sub
这个插件是存在于我所有的Excel实例中,但是您可以使用Kazjaw的想法,只将加载项加载到Excel的特定实例中。