VBA Addins:事件不起作用

时间:2012-05-05 23:46:49

标签: excel excel-vba excel-addins vba

我只想在所有工作簿(包括或不包含宏)中捕获打开和保存事件。 据我所知,我需要AddIn和Event -enabled代码。我在互联网上找到了很多例子。我学习了stackoverflow示例,例如:How can an Excel Add-In respond to events in any worksheet? 但它只是不起作用。没有人报告任何问题。所以,我想我在这里有一个简单的错误。 我有下一个Addin,例如:

课程模块(ExcelEventCapture) - 私人:

Option Explicit
Public WithEvents ExcelApp As Excel.Application

Private Sub Class_Initialize()
Set ExcelApp = New Excel.Application
ExcelApp.EnableEvents = True
MsgBox "ExcelApp OK"
End Sub

Private Sub ExcelApp_NewWorkbook(ByVal Wb As Workbook)
Wb.Close savechanges:=False
MsgBox "Sorry - you can't create workbooks in this system!"
End Sub

此代码放在ThisWorkbook中:

Option Explicit
Private ExcelEvents As ExcelEventCapture
Private Sub Workbook_Open()
Set ExcelEvents = New ExcelEventCapture
MsgBox "ExcelEvents OK"
End Sub

每次保存/修改此代码后,我都会使用Add-Ins manager来关闭/打开此插件。打开后,我看到“ExcelApp OK”,“ExcelEvents OK”。但是当我创建新工作簿时,没有事件发生。其他事件也没有处理。我尝试使用2007/2010 Excel。结果一样。 请帮忙。

1 个答案:

答案 0 :(得分:2)

您的代码不太正确:

课程模块(ExcelEventCapture)

Option Explicit

Public WithEvents ExcelApp As Application

Private Sub ExcelApp_NewWorkbook(ByVal Wb As Workbook)
    Wb.Close savechanges:=False
    MsgBox "Sorry - you can't create workbooks in this system!"
End Sub

此代码放在ThisWorkbook中:

Option Explicit

Private ExcelEvents As New ExcelEventCapture

Private Sub Workbook_Open()
    Set ExcelEvents.ExcelApp = Application
    MsgBox "ExcelEvents OK"
End Sub