从Excel VBA控件内部自引用

我试图从button的click事件中获取button控件的属性值,而不使用button的名称(因为我想为Excel工作表上的每个button使用相同的代码)。

经过大量的研究,我看到许多参考文献尝试以下内容:

Me.ActiveControl.name 

要么

 Me.Shapes(Application.Caller).Name 

但是,这两个从Excel内执行时会引发错误。 请注意,我正在使用Excel 2010。

提前感谢您的帮助。 背风处

你想要什么是可能的,但是你需要创build一个Class

做这个。

插入一个类模块并粘贴这个代码。

 Option Explicit Public WithEvents MyButton As MSForms.CommandButton Private Sub MyButton_Click() MsgBox MyButton.Name End Sub 

在这里输入图像描述

下一步插入一个模块,并将此代码放在那里

 Dim shpButtons() As New Class1 Sub StartCode() Dim shp As Shape Dim btnCount As Long ReDim shpButtons(1 To 1) btnCount = 0 For Each shp In ActiveSheet.Shapes If shp.OLEFormat.Object.OLEType = xlOLEControl Then btnCount = btnCount + 1 ReDim Preserve shpButtons(1 To btnCount) Set shpButtons(btnCount).MyButton = shp.OLEFormat.Object.Object End If Next End Sub Sub StopCode() Dim iBtn As Long On Error Resume Next For iBtn = LBound(shpButtons) To UBound(shpButtons) Set shpButtons(iBtn).TheText = Nothing Next End Sub 

在这里输入图像描述

现在只需运行Sub StartCode()

接下来当你点击ActiveX CommandButton时,你会得到它的名字。

在这里输入图像描述

尝试ActiveSheet.Shapes(Application.Caller).Name