每当在Excel工作簿中创建新工作表时,我都会尝试打开一个消息框。我还想在创建新工作簿时打开一个消息框。到目前为止,我能够像这样完成新的工作簿消息:
我有一个名为cl_AppEvents的类模块,其中包含:
Public WithEvents AppEvent As Application
Public WithEvents WB As Workbook
Public WithEvents Sh As Worksheet
Public Sub AppEvent_NewWorkbook(ByVal WB As Workbook)
MsgBox ("New Workbook")
End Sub
Public Sub WB_NewSheet(ByVal Sh As Object)
MsgBox ("New Worksheet")
End Sub
以下是我初始化应用程序事件的代码:
Dim myAppEvent As New cl_AppEvents
Sub InitializeAppEvent()
Set myAppEvent.AppEvent = Application
End Sub
我尝试过这样的事情:
Public Sub AppEvent_NewWorkbook(ByVal WB As Workbook)
MsgBox ("New Workbook")
WB_NewSheet(ByVal Sh As Workbook)
End Sub
但这只是给了我一个对象属性错误。那么我如何为NewWorkbook事件中引用的新工作簿WB启用NewSheet事件?
答案 0 :(得分:1)
clsAppEvt:
Public WithEvents AppEvent As Application
Public WbColl As New Collection
Public Sub AppEvent_NewWorkbook(ByVal WB As Workbook)
Dim oWB As clsWbEvt
MsgBox ("New Workbook")
Set oWB = New clsWbEvt
oWB.Init WB
WbColl.Add oWB
End Sub
Public Sub Init(app As Application)
Set Me.AppEvent = app
End Sub
clsWbEvt:
Public WithEvents WB As Workbook
Public Sub WB_NewSheet(ByVal Sh As Object)
MsgBox ("New Worksheet")
End Sub
Public Sub Init(wbk As Workbook)
Set Me.WB = wbk
End Sub
常规模块:
Dim oApp As clsAppEvt
Sub Setup()
Set oApp = New clsAppEvt
oApp.Init Application
End Sub
答案 1 :(得分:0)
尝试向您的类添加Initialize事件处理程序,并设置Workbook对象!
Private Sub Class_Initialize()
Set WB = Application.ActiveWorkbook
End Sub
Public Sub WB_NewSheet(ByVal Sh As Object)
MsgBox ("New Worksheet")
End Sub
我用你的代码尝试了这个,它工作得很好..
当然,顺便说一句,这只适用于第一个工作簿,工作表事件不会为新工作簿触发!HTH 菲利普