Search code examples
excelvbaexcel-2010userform

How to Loop Userform Controls Events?


I want a loop for userform controls events.

I have six image items;

button1
button1_hover 
button2 
button2_hover 
button3 
button3_hover

I used the event called MouseMove to create a hover statement. I used this method like this;

Private Sub button1_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

button1.Visible = False
button1_hover.Visible = True

End Sub

Private Sub button2_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

button2.Visible = False
button2_hover.Visible = True

End Sub

Private Sub button3_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

button3.Visible = False
button3_hover.Visible = True

End Sub

Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

For i = 1 To 4
 Me.Controls("button" & i).Visible = True
 Me.Controls("button" & i & "_hover").Visible = False
 Me.Controls("button" & i & "_click").Visible = False
Next

End Sub

It works but I want to use the three mousemove events in a loop.


Solution

  • You can use a custom class to capture the MouseMove for the controls you're interested in. Here's a simple example which just swaps out the backcolor for command buttons.

    Your use case would be a little more complex, but the same basic approach would work.

    Option Explicit
    
    Private colButtons As Collection
    
    Private Sub UserForm_Activate()
        Dim ctl
        Set colButtons = New Collection
        'loop over controls and look for buttons (for example)
        For Each ctl In Me.Controls
            If TypeName(ctl) = "CommandButton" Then
                colButtons.Add getHover(ctl) 'create an instance of hover using ctl
            End If
        Next
    End Sub
    
    Function getHover(ctl)
        Dim rv As New hover
        Set rv.btn = ctl
        Set getHover = rv
    End Function
    
    Private Sub UserForm_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
                                   ByVal X As Single, ByVal Y As Single)
        Dim o As hover
        'clear all the button backcolors in colButtons
        For Each o In colButtons
            o.btn.BackColor = RGB(200, 200, 200)
        Next o
    End Sub
    

    Custom class hover - objects of this class hold a reference to the provided control and capture its MouseMove event

    Option Explicit
    
    Public WithEvents btn As MSForms.CommandButton '<< note WithEvents
    
    Private Sub btn_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, _
                              ByVal X As Single, ByVal Y As Single)
        btn.BackColor = vbYellow
    End Sub