首页 > 解决方案 > 如何循环用户窗体控件事件?

问题描述

我想要一个用户窗体控件事件的循环。

我有六个图像项;

button1
button1_hover 
button2 
button2_hover 
button3 
button3_hover

我使用名为 MouseMove 的事件来创建悬停语句。我是这样使用这种方法的;

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

它有效,但我想在循环中使用三个 mousemove 事件。

标签: excelvbaexcel-2010userform

解决方案


您可以使用自定义类来捕获MouseMove您感兴趣的控件。这是一个简单的示例,它只是将背景颜色换成命令按钮。

您的用例会稍微复杂一些,但同样的基本方法会起作用。

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

自定义类hover- 此类的对象持有对提供的控件的引用并捕获其MouseMove事件

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

推荐阅读