0

I'm try to write a wrapper class for getting events. This is a not working (EDIT: not show the message box) simple example: Where is the mistake?

' CLASSE1
Private WithEvents frm As Access.Form
Private Const Evented As String = "[Event Procedure]"
Public Sub Init(pFrm As Access.Form)
    Set frm = pFrm
    frm.OnLoad = Evented
End Sub
Private Sub frm_Load()
    MsgBox "OK!" 'NOT SHOW
End Sub

'Form1
Private SL As Classe1
Private Sub Form_Load()
    Set SL = New Classe1
    SL.Init Me
End Sub
4
  • the "OK" message is not displayed Commented Jan 29, 2021 at 9:14
  • 3
    The form's Load() event has already been raised. Try a different event for testing. Commented Jan 29, 2021 at 9:26
  • I am attempting code. I put the CLASSE1 code in general module and immediately show a compile error on Private WithEvents frm As Access.Form. This must be in form module. If I put all code behind form then Private SL As Classe1 errors because it is not in header. If I move it to header get error "User-defined type not defined". Commented Jan 29, 2021 at 9:31
  • @June7 I have a Class Module "Classe1" and a Fom module Commented Jan 29, 2021 at 9:39

1 Answer 1

1

You have mixed up the form load. This works:

Class1:

Option Compare Database
Option Explicit

Private WithEvents frm As Access.Form
Private Const Evented As String = "[Event Procedure]"

Public Sub Initialize(pFrm As Access.Form)
    Set frm = pFrm
    frm.OnCurrent = Evented
End Sub

Public Sub Terminate()
    Set frm = Nothing
End Sub

Private Sub frm_Current()
    MsgBox "OK"
End Sub

Form1:

Option Compare Database
Option Explicit

Private FormCollection   As Collection

Private Sub Form_Load()

    Dim EventProcedure  As Class1
    
    Set EventProcedure = New Class1
    Set FormCollection = New Collection

    EventProcedure.Initialize Me.Form
    FormCollection.Add EventProcedure, Me.Name

    Set EventProcedure = Nothing
    
End Sub

Private Sub Form_Unload(Cancel As Integer)

    ' Unload events for all colour value textboxes.
    
    Dim EventProcedure  As Class1
    
    For Each EventProcedure In FormCollection
        EventProcedure.Terminate
    Next
    
    Set EventProcedure = Nothing
    Set FormCollection = Nothing

End Sub
Sign up to request clarification or add additional context in comments.

3 Comments

Spelling out Init is not needed. @KostasK. comments have cause and correction.
I've cut down the code from an example of mine: VBA.ModernTheme.
That avoids the entire problem, namely, you're adding an event for current, not for load, and the problem is that the class is initialized on load so it's too late to hook into the load event.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.