excel - 如何循环用户窗体控件事件?
问题描述
我想要一个用户窗体控件事件的循环。
我有六个图像项;
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 事件。
解决方案
您可以使用自定义类来捕获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
推荐阅读
- r - 断开 R 中的所有 MySQL 连接
- arrays - Excel公式:使用条件计算数组元素
- javascript - 将引导类添加到 JS 类
- angular - 我在 Angular4 中的订阅中的数据为空
- excel - Excel VBA 用户窗体退出
- java - 为什么这会在运行时导致 ArrayIndexOutOfBoundsException?
- android - 如何使用 GridView 变量从 onCreateView 类到片段中的另一个类?
- wpf - Wpf 应用程序作为单个可执行文件
- ios - 在 iOS 中运行 UI 测试时如何在应用程序中打断点?
- github - 成功克隆并推送了一个分叉的 repo,在 Github 上无法读取