Search code examples
excelvbadynamicuser-controlsmouseover

Excel VBA Which UserForm Control Triggered Shared MouseOver Class Event?


How do I return the name of the userform control that triggered the mouseover class event?

This sounds so simple but honestly I've been racking my brain trying to find the correct syntax...

Here is my userform module:

Option Explicit
Dim dArray() As New Class1

Sub Build_Controls()
Dim dImage As Object, i As Integer

For i = 1 To 3
Set dImage = UserForm1.Controls.Add("Forms.Image.1", i, True)
    With dImage
        .Left = (25 * i) + 20
        .Width = 20
        .Top = 10
        .Height = 20
    End With
    ReDim Preserve dArray(1 To i)
    Set dArray(i).dImages = dImage
Next i

End Sub

Private Sub UserForm_Activate()
Build_Controls
End Sub

I dynamically create three image controls at runtime aptly named "1", "2", and "3".

I assign each control a mouseover event found in the following class module called "Class1":

Public WithEvents dImages As MSForms.Image
Private Sub dImages_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
MsgBox ("Control Name") 'Which control was triggered?
End Sub

How can I make the MsgBox contain the name of the control that triggered the event?

Me.dImages.Name              'x
ActiveControl.Name           'x
Screen.ActiveControl.Name    'x    
UserForm1.ActiveControl.Name 'x

Any help is appreciated.

Thanks,

Mr. J


Solution

  • use this in the class module

    do not use msgbox because it puts the VBA editor into background

    use Debug.Print, then you can watch the values change on the fly in the immediate window

    put a breakpoint at the debug.print line and then examine the dImages object in the watch window ( that is how i got the name attribute )

    Option Explicit
    
    Public WithEvents dImages As MSForms.Image
    '
    
    Private Sub dImages_Click()
        Debug.Print dImages.Name
    End Sub
    '
    
    Private Sub dImages_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
        Debug.Print dImages.Name
    End Sub