从 Excel VBA 控件内部进行自引用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20293850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Self-referencing from inside an Excel VBA control
提问by LeeBarnes
I'm trying to get a property value of a button control from inside the button's click event without using the button's name (since I want to use the same code for each of many buttons on the Excel sheet).
我试图在不使用按钮名称的情况下从按钮的单击事件内部获取按钮控件的属性值(因为我想对 Excel 工作表上的许多按钮中的每一个使用相同的代码)。
After much research, I see many references to try the following:
经过大量研究,我看到很多参考资料可以尝试以下方法:
Me.ActiveControl.name
or
或者
Me.Shapes(Application.Caller).Name
However, both of those throw an error when executed from within Excel. Note that I'm using Excel 2010.
但是,当从 Excel 中执行时,这两者都会引发错误。请注意,我使用的是 Excel 2010。
Thanks for any help in advance. Lee
提前感谢您的任何帮助。李
回答by Siddharth Rout
What you want is possible but for that you need to create a Class
你想要的是可能的,但为此你需要创建一个 Class
Do this.
做这个。
Insert a Class Module and paste this code there.
插入一个类模块并将此代码粘贴到那里。
Option Explicit
Public WithEvents MyButton As MSForms.CommandButton
Private Sub MyButton_Click()
MsgBox MyButton.Name
End Sub
Next Insert a module and place this code there
Next 插入一个模块并将此代码放在那里
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
Now simply run the Sub StartCode()
现在只需运行 Sub StartCode()
Next when you click the ActiveX CommandButton then you will get it's name.
接下来,当您单击 ActiveX 命令按钮时,您将获得它的名称。
回答by Blackhawk
Try ActiveSheet.Shapes(Application.Caller).Name
尝试 ActiveSheet.Shapes(Application.Caller).Name