[英]VBA Excel 2010 - How to assign a macro to a command button that was made with a macro
我有一个创建命令按钮的宏,但是我无法为VBA中的按钮分配任何宏
已经查看了此链接,但是它是针对用户表单的(但是我不足以更改它以适应我的需求)
我当前正在调试的代码如下,我想我需要在With
语句中添加一些内容,但我不知道它会是什么
Dim MyR As Range, MyB As OLEObject
Dim MyR_T As Long, MyR_L As Long
Set MyR = Range("I3") 'just an example - you get that from your own script
MyR_T = MyR.Top 'capture positions
MyR_L = MyR.Left '...
'create button
Set MyB = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
Link:=False, DisplayAsIcon:=False)
'set main button properties
With MyB
.Name = "MyPrecodedButton" 'important - code must exist ... see below
.Object.Caption = "Load UseForm"
.Top = MyR_T
.Left = MyR_L
.Width = 130
.Height = 30
.Placement = xlMoveAndSize
.PrintObject = True 'or false as per your taste
End With
因此,从您自己发布的链接中,您的代码如下所示:
Set UF = ActiveWorkbook.VBProject.VBComponents("Name_of_the_userform")
With UF.CodeModule
.InsertLines 2, _
"Private Sub " & MyB.Name & "_Click()" & Chr(13) & _
"****HERE COMES YOUR FUNCTION CALL FOR THE BUTTON****" & Chr(13) & _
"End Sub"
End With
但这仅适用于activeX按钮。 它的功能相当强大……所以,如果您有更好的解决方案,我将不建议您这样做。 它的作用是:每个ActiveX Button都具有带有以下语法的onclick函数:“ ButtonName_Click()”如果您在代码中的某处放置了此行,则将在单击时执行。 现在,代码执行的操作(如您发布的链接中所示)是将这些函数写入用户窗体代码中。
使用.onAction方法
像这样
Sheets("someVeryFunnySheetName").buttons("someSeriousButtonName").onAction = "macroName"
这是一个示例,如果您想将参数传递给该宏(我认为axleOutputSHeetCounter是一些整数)
With chartSheet.Buttons("closeOutputSheet")
.OnAction = "'Module7_Axle.closeOutputSheet """ & axleOutputSheetCounter & """'"
.Characters.text = "Delete sheet"
.Characters.Font.Size = 16
End With
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.