简体   繁体   English

将宏分配给在运行时VBA中创建的按钮

[英]Assign macro to a button created in run time VBA

My question is basically answered in this post 我的问题基本上在这篇文章中得到了回答

But instead of the class code below: 但是代替下面的类代码:

Sub CmdEvents_Click()
   MsgBox "Hello World"
End Sub

I need to run this code (it's just a sample, I want to use the name of the button clicked later in the program) 我需要运行此代码(这只是一个示例,我想使用稍后在程序中单击的按钮的名称)

Sub CmdEvents_Click()
Dim mvCtrl As Control
Set mvCtrl = Me.ActiveControl
MsgBox mvCtrl.Name
End Sub

But this code above will NOT, by any means return correctly the Name of the button I just created in run time in the message box. 但是上面的代码不会以任何方式正确返回我在运行时在消息框中刚刚创建的按钮的名称。

It returns "Button 6".... I did a search in my workbook and I don't even have this name. 它返回“按钮6”。...我在工作簿中进行了搜索,甚至没有这个名字。

I actually I modified the original code from the link above to get the names of the buttons all from a list. 实际上,我修改了上面链接中的原始代码,以从列表中获取所有按钮的名称。 This way I can modify the list, thus modifying the name of the buttons, or caption if I want to. 这样,我可以修改列表,从而修改按钮的名称或标题(如果需要)。 And this Button 6 doesn't even exists in my list. 这个按钮6甚至不在我的列表中。

I made some traps in my code, showing message boxes for the variable I use to get the button name from, and it's correct, it's carrying the string I want to name my button before it creates it. 我在代码中做了一些陷阱,显示了用于从中获取按钮名称的变量的消息框,这是正确的,它包含了在创建按钮之前要为其命名的字符串。

Assuming you followed the post you linked to, your class instance already contains a variable CmdEvents which references the clicked button, so you can use 假设您跟踪了链接到的帖子,则您的类实例已经包含一个变量CmdEvents ,该变量引用了clicked按钮,因此您可以使用

Msgbox CmdEvents.Name 

If your code is different, it would be useful to post the relevant parts so we can see what's going on. 如果您的代码不同,则发布相关部分会很有用,这样我们就可以看到发生了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM