Skip to content

Inspection for out-of-scope event source #3475

Open
@retailcoder

Description

@retailcoder

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    code-path-analysisInvolves simulating execution paths / interpreting the user code ..to an extent.difficulty-03-duckInvolves more challenging problems and/or developing within and revising the internals APIenhancementFeature requests, or enhancements to existing features. Ideas. Anything within the project's scope.feature-inspection-quickfixesfeature-inspectionsup-for-grabsUse this label in conjunction with a difficulty level label, e.g. difficulty-02-ducky

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions