将单击 VBA 函数分配给 Excel 用户窗体上动态创建的按钮
我使用以下代码在 Excel 用户窗体上动态创建按钮:
With Me.CurrentFrame.Controls.Add("Forms.CommandButton.1")
.Caption = "XYZ"
.name = "AButton"
.Font.Bold = True
.ForeColor = &HFF&
... blah blah blah
End With
我想指定一个函数在单击这些按钮时运行,但我找不到直接的方法来执行此操作,因为没有属性作为按钮本身。
有没有办法使用上面的习惯用法来做到这一点? 我应该以不同的方式来处理这整件事吗?
I'm creating buttons dynamically on an Excel userform with the following code:
With Me.CurrentFrame.Controls.Add("Forms.CommandButton.1")
.Caption = "XYZ"
.name = "AButton"
.Font.Bold = True
.ForeColor = &HFF&
... blah blah blah
End With
I'd like to assign a function to run when these buttons are clicked, but I can't find a straightforward way to do this since there's no property as part of the button itself.
Is there a way to do this using the above idiom? Should I be going about this whole thing in a different way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在Excel表单中动态添加控件事件; 您需要首先在类模块中添加事件。 对于我的示例,我将添加一个名为 clsTEST 的类模块,其中包含一个事件 btn_click()
如您所见,唯一要做的就是将按钮上的标题设置为您单击它的次数。
接下来,在表单代码中输入以下内容:
当您激活表单时,它将创建一个按钮。 每次单击该按钮时,标题都会更改。
To add a control event dynamically in an Excel form; you need to first add the event(s) in a class module. For my example, I am going to add a class module named clsTEST with one event, btn_click()
As you can see, the only thing this will do is set the caption on the button to then number of times you clicked it.
Next, in the form code enter the following:
When you activate the form, it will create a button. every time you click on the button the caption will change.
您需要为每个按钮动态创建代码/事件处理程序。
这需要做一些工作 - 请参阅此处:http://navpadexcel.blogspot.com/2006/11 /httpwwwcpearsoncomexcelvbehtm.html
更好的方法可能是提前在表单上创建一堆按钮(您认为需要的数量)。 还要创建事件处理程序代码。 最初将它们全部隐藏。
然后,当您的表单打开时,您可以动态更改按钮标题,使它们可见并移动它们。 您最初创建的事件代码将按预期链接到激活的按钮。
You need to dynamically create code / event handlers for each button.
It take a bit of doing - see here: http://navpadexcel.blogspot.com/2006/11/httpwwwcpearsoncomexcelvbehtm.html
A better way might be to create a bunch of buttons on the form (as many as you think you'll need) ahead of time. Create the event handler code as well. Make them all hidden initially.
Then when your form opens you can dynamically change the button captions, make them visible and move them around. The event code you created initially will be linked to the activated buttons as expected.
下面的代码应该可以工作
The below code should be working
我也一直在关注这个。 似乎您可以使用 onClick 属性运行宏:
然后使用该名称创建一个运行所需函数的宏。
这是我解决这个问题的技巧,直到我找到更好的东西。
I've been looking at this as well. Seems you can run a macro by using the onClick property:
Then create a macro by that name that runs the desired function.
This is my hack around this until I find something better.