You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel用户窗体鼠标悬停时获取动态创建按钮控件名称的方法

解决思路

方法1:利用控件的Tag属性预存编号

动态创建按钮时,直接把需要的数字存入按钮的Tag属性,后续无需从控件名称提取,也不依赖焦点:

' 动态创建按钮时的代码
Dim i As Integer
Dim newBtn As CommandButton
For i = 1 To 5
    Set newBtn = Me.Controls.Add("Forms.CommandButton.1", "BtnFund" & i)
    newBtn.Tag = i ' 将末尾数字存入Tag
    newBtn.Caption = "基金" & i
    newBtn.OnMouseMove = "[Event Procedure]" ' 绑定悬停事件
Next i

在悬停事件中直接读取Tag:

Private Sub BtnFund_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    Dim FundNo As Integer
    ' 通过Application.Caller获取触发事件的控件名称,再读取其Tag
    FundNo = Me.Controls(Application.Caller).Tag
    ' 执行后续逻辑
End Sub

方法2:用Application.Caller获取触发事件的控件名称

Application.Caller可以直接返回触发当前事件的控件名称,无需依赖ActiveControl(不受焦点影响):

Private Sub BtnFund_MouseMove(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    Dim ctrlName As String
    Dim FundNo As Integer
    ctrlName = Application.Caller ' 获取触发事件的控件名称
    FundNo = CInt(Right(ctrlName, 1)) ' 提取末尾数字并转成整数
    ' 执行后续逻辑
End Sub

方法3:绑定事件时直接传递控件实例(适用于VB.NET等支持委托的环境)

如果是VB.NET这类平台,动态创建按钮时可以绑定带参数的事件处理,直接拿到控件实例:

For i As Integer = 1 To 5
    Dim btn As New Button()
    btn.Name = "BtnFund" & i
    btn.Text = "基金" & i
    ' 绑定MouseHover事件,直接获取按钮实例
    AddHandler btn.MouseHover, Sub(sender As Object, e As EventArgs)
                                   Dim targetBtn As Button = DirectCast(sender, Button)
                                   Dim FundNo As Integer = CInt(targetBtn.Name.Last().ToString())
                                   ' 执行后续逻辑
                               End Sub
    Me.Controls.Add(btn)
Next

内容的提问来源于stack exchange,提问作者Mark Stephens

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:36:14