单击 Excel 中 VBA 框架内按钮的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15510967/
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
Click Event for buttons inside Frames for VBA in Excel
提问by Robino
In Excel I insert an ActiveX Frame into a worksheet. Right clicking this frame allows me to select:
在 Excel 中,我将 ActiveX 框架插入到工作表中。右键单击此框架允许我选择:
Frame Object>Edit
框架对象>编辑
Now I am able to add a button to this frame. Great.
现在我可以向这个框架添加一个按钮。伟大的。
How do I add a _Click event to this button so that it will run a macro?
如何向此按钮添加 _Click 事件以便它运行宏?
回答by Zhenya
Basically, what you need to do is to create you own class, for instance, "XButton". Inside this 'XButton' there will be an event handler for the button object that is inside the frame.
基本上,您需要做的是创建自己的类,例如“XButton”。在这个“XButton”中,将有一个用于框架内按钮对象的事件处理程序。
So you can handle all of the events that are sent by 'btn' and forward it further. Then you will have to create a custom interface (empty class) IXButtonEventHandler, that will look something like this:
因此,您可以处理“btn”发送的所有事件并进一步转发。然后你必须创建一个自定义接口(空类)IXButtonEventHandler,它看起来像这样:
Option Explicit
Public Sub Click(Sender as XButton)
End Sub
So, your custom class XButtonwill look like this:
因此,您的自定义类XButton将如下所示:
Private WithEvents btn as MSForms.CommandButton
Private mEventHandler as IXButtonEventHandler
Public Sub CreateObject(EventHandlerOf as MSForms.CommandButton, EventHandler as IXButtonEventHandler)
Set btn = EventHandlerOf
Set mEventHandler = EventHandler
End Sub
Private Sub btn_Click()
If not mEventHandler is Nothing then mEventHandler.Click(Me)
End Sub
Let's say, your Workbook will be the event handler and will need to implement the IXButtonEventHandler interface, for instance:
假设您的工作簿将成为事件处理程序,并且需要实现 IXButtonEventHandler 接口,例如:
Implements IXButtonEventHandler
Private Sub IXButtonEventHandler_Click(Sender as XButton)
'your code
End Sub
On Workbook_Load or whatnot you will need to create a collection of XButtons and attach them to your frame controls:
在 Workbook_Load 或诸如此类的东西上,您需要创建 XButton 集合并将它们附加到您的框架控件:
Dim xbtn as Collection
Private Sub AttachButtons()
Set xbtn = New Collection
Dim i as Long
For i = 0 to 3
Dim xb as New XButton
xb.CreateObject <YourFrame>.Controls("CommandButton" & Cstr(i)), Me
xbtn.Add xb
Next i
End Sub