Solved WithEvents Class

KitaYama

Well-known member
Local time
Today, 23:15
Joined
Jan 6, 2022
Messages
1,885
My first steps to learn how to use WithEvents in a class module.
Here's a simplified version of what I have in a class module called clsFrm:
Code:
Option Explicit

Private WithEvents m_form As Access.Form
Private WithEvents m_Closebtn As Access.CommandButton
Const fEvents As String = "[Event Procedure]"

Public Sub InitCls(frm As Access.Form, btn As Access.CommandButton)
    Set m_form = frm
    Set m_Closebtn = btn
    m_Closebtn.OnClick = fEvents
End Sub

Private Sub m_Closebtn_Click()
    MsgBox ""
End Sub

ln the OnLoad events of a form with only one button I have this:
Code:
Private Sub Form_Load()
     Dim frm As New clsFrm

     frm.InitCls Me, btnCloseMe
End Sub

When I click the button (btnCloseme), nothing happens.

First question : What I'm doing wrong here?
Second question: I'm looking for some easy-to-understand tutorials for using WithEvents in Access classes. My google search didn't help that much. Can you share some sites that can be a good start point?

Thanks for any kind of advice.
 
Last edited:
You could move your frm variable declaration to module level like
Code:
Private frm As New clsFrm

Private Sub Form_Load()
     frm.InitCls Me, btnCloseMe
End Sub

That way you'll have it available for the other events.
 
In this code, the class reference is destroyed when the procedure is exited.
Code:
Private Sub Form_Load()
     Dim frm As New clsFrm

     frm.InitCls Me, btnCloseMe
     ' frm => nothing after end of sub

End Sub
=> As Edgar already showed, the class reference must be preserved.
I would just not declare them New so you can check for nothing later.

Code:
private m_Frm as clsFrm

Private Sub Form_Load()
     set m_Frm = new clsFrm
     m_Frm.InitCls Me, btnCloseMe
End Sub

Private Sub Form_Unload(Cancel As Integer)
     set m_Frm = nothing
End Sub

Note that you create circular references in your code. The form keeps the instance of clsFrm alive and clsForm keeps the instance of the form.
=> Remove the reference from clsFrm on unload. Ideally, also respond to Unload in clsFrm and remove the form reference there.
 
Have a read, probably one of the most informative sources regarding With Events and Class Modules...

 

Users who are viewing this thread

Back
Top Bottom