Reputation: 78
I have a problem getting any event firing from controls embedded in Class Modules in VBA Access. Despite many (many!) conversations in various forums related to this one, I haven't found any that help me. As far as I can tell I am following all their advices (mainly, I always use "Access.Control", "Access.Label" and so on so it is always the same library that is used, and the reference still exists at the moment the event should fire...), but it still doesn't fire! In the same project I have the same problem in several classes; I will take the example of a group of labels on a form.
The load event of the form creates a first, big group like that:
Private Sub Form_Load()
...
set mGroups = new CDocTree
mGroups.Make Me
End Sub
In CDocTree there are three member variables declared like that:
Private WithEvents mVVPlan As CDocGroup
Private WithEvents mTestPlan As CDocGroup
Private mFrm As Form_FrmAlphaDocuments
and the method Make essentially does this:
Public Sub Make(frm As Access.Form)
Set mFrm = frm
With mFrm
Set mVVPlan = New CDocGroup
mVVPlan .Make .LblVVPlanBox, .LblVVPlanRef
Set mTestPlan = New CDocGroup
mTestPlan .Make .LblTestPlanBox, .LblTestPlanRef
End With
End Sub
Finally the class CDocGroup is defined like that:
Private WithEvents mBox As Access.Label
Private WithEvents mRef As Access.Label
Public Event Clicked(grp As CDocGroup)
Public Sub Make(box As Access.Label, ref As Access.Label)
...
Set mBox = box
Set mRef = ref
End Sub
Private Sub mBox_Click()
Debug.Print "Event Click fired in CDocGroup on " & mBox.Name
RaiseEvent Clicked(Me)
End Sub
Private Sub mRef_Click()
Debug.Print "Event Click fired in CDocGroup on " & mRef.Name
RaiseEvent Clicked(Me)
End Sub
That's it: the code never gets in mBox_Click or mRef_Click. What do I do wrong?
Upvotes: 1
Views: 1265
Reputation: 673
If anybody comes across this post like me, trying to figure out why the events aren't firing, there is a far simpler solution on another forum.
Basically when you set your mBox / mRef in the class module do the following:
mBox.OnClick = "[Event Procedure]"
mRef.OnClick = "[Event Procedure]"
This will let the class module know, that there is an event it has to execute. So there is no need to declare all the subs in your forms code.
Upvotes: 1
Reputation: 78
Thanks VBlades, it does the trick.
Although it is infuriating that something like this should be necessary, I can indeed verify that if I put a declaration for some of the controls and not for others, my events fire only for the controls that have the empty event declaration in the form's module.
So to be clear, in the form's module, for each control that I need to react, I add an empty declaration:
Private Sub LblVVPlanBox_Click()
End Sub
No code at all in it, but now the event in my class fires and the code in the class is executed. It is kind of ugly, but still better than copying 20 times the same instructions in the form's module.
Upvotes: 2