我正在努力了解如何使用VBA中的类模块创建自定义事件。
我将简单的以下示例放在一起。你在A1和B1中放了一个值,然后重新激活工作表来计算两者之和,然后我希望事件发生时会发出警告计算,但没有任何反应。
我非常感谢解决这个例子的任何帮助。
课程模块cCalc:
Dim m_wks As Worksheet
Public Event BeforeCalc()
Property Set Worksheet(wks As Worksheet)
Set m_wks = wks
End Property
Public Sub Calc()
Dim dVal1 As Double
Dim dVal2 As Double
With m_wks
dVal1 = .Range("A1").Value
dVal2 = .Range("B1").Value
RaiseEvent BeforeCalc
.Range("C1").Value = dVal1 + dVal2
End With
End Sub
在mGlobal模块中:
Public gCalc As cCalc
在Sheet1背后的代码中:
Private WithEvents calcEvent As cCalc
Private Sub calcEvent_BeforeCalc()
MsgBox "About to Calc!", vbInformation
End Sub
Private Sub Worksheet_Activate()
Set gCalc = New cCalc
Set gCalc.Worksheet = ActiveSheet
gCalc.Calc
End Sub
答案 0 :(得分:2)
您无法在模块中声明事件驱动的类。您需要将gModule中的cCalc引用设置为等于Sheet1中声明为WithEvents的对象。将Sheet1中的代码更改为我在下面编写的代码,它将起作用:
Private WithEvents calcEvent As cCalc
Private Sub calcEvent_BeforeCalc()
MsgBox "About to Calc!", vbInformation
End Sub
Private Sub Worksheet_Activate()
Set calcEvent = New cCalc 'Instantiate the WithEvents object above
Set mGlobal.gCalc = calcEvent 'Set the object declared in gModule
Set mGlobal.gCalc.Worksheet = ActiveSheet
mGlobal.gCalc.Calc
End Sub
请注意,这是使用你在gModule中放入的变量...实际调用的事件仍然是 calcEvent_BeforeCalc(),这很好,因为你可以定义n个对象在gModule中,当触发事件时,它将触发相同的事件代码。
为了简化代码,你总是可以写:
Private Sub Worksheet_Activate()
Set calcEvent = New cCalc
Set calcEvent.Worksheet = ActiveSheet
calcEvent.Calc
End Sub