Description
This is particularly common when toying with dynamic MSForms
controls:
Option Explicit
Private WithEvents source As MSForms.CommandButton
Public Sub Init(ByVal ctrl As MSForms.CommandButton)
Set source = ctrl
End Sub
Private Sub source_Click()
'do something
End Sub
And then in the form's code-behind, user sets the event source, but lets it go out of scope:
Public Sub Setup()
Dim myButton As AwesomeButton
Set myButton = New AwesomeButton
myButton.Init(Me.Controls.Add(bstrProgID:="Forms.CommandButton.1", Name:="MyButton", Visible:=True))
End Sub
As a result, source_Click
is never invoked, because the source
is out of scope as soon as Setup
exits.
Rubberduck should be able to issue a warning about the event source going out of scope, and possibly even suggest promoting myButton
to a private field. If the assignment is inside a loop body, then the fix would be to have a module-level Collection
to keep the object references around, and .Add
the instances to the collection in the loop.
This should hold true for any class that encapsulates a WithEvents
field. Particular attention needs to be taken in the wording of the meta-description for that inspection... it's easy to get confusing!