Carpenter
Carpenter

Reputation: 13

Update form with events

I have an UserForm (frmProgress) which should display the progress of the process with a label. In a class module (clsProgressForm) I create the UserForm as follows:

Option Explicit

Public Event UpdateProgress(ByVal str As String)

Private Sub Class_Initialize()
    Dim frm As frmProgress
    Set frm = New frmProgress
    Load frm 
    frm.Show vbModeless

    RaiseEvent UpdateProgress("test")
End Sub

The UserForm contains the following code:

Option Explicit

Private WithEvents frm As MSForms.UserForm

Private Sub frm_UpdateProgress(ByVal str As String)
    lblUpdate.Caption = str
End Sub

However the frm_UpdateProgress event on the UserForm is never called. How can I update the UserForm by using events?

Upvotes: 1

Views: 527

Answers (1)

Blackhawk
Blackhawk

Reputation: 6140

If you want this specific example to work the way you are thinking, you would need to change a couple things:

frmProgress:

Option Explicit

Public WithEvents oProgressFormClassInstance As clsProgressForm
'The WithEvents here implies that whenever the specific object referenced by this variable
'throws an event, it will trigger the event handler for that event in this class (form)

Private Sub oProgressFormClassInstance_UpdateProgress(ByVal str As String)
    lblUpdate.Caption = str
End Sub

clsProgressForm:

Option Explicit

Public Event UpdateProgress(ByVal str As String)

Private Sub Class_Initialize()
    Dim frm As frmProgress
    Set frm = New frmProgress

    Set frm.oProgressFormClassInstance = Me

    Load frm
    frm.Show vbModeless

    RaiseEvent UpdateProgress("test")
End Sub

A test module mdlTest:

Public Sub Test()
    Dim oProgressForm As clsProgressForm
    Set oProgressForm = New clsProgressForm
End Sub

Run the Test function to see the form and class in action. If you are still unsure of how events work, let me know and I can expand the answer.

Upvotes: 1

Related Questions