VBA Excel 2010 – 如何将macros指定给使用macros创build的命令button

我有一个macros创build一个命令button,但是我无法将任何macros分配给VBA中的button

已经看过这个链接,但它的用户表单(但我不够好,能够改变它,以满足我需要)

我现在正在testing的代码是在下面,我猜我需要添加一些东西的声明,但我不知道它会是什么

 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 

使用.onAction方法

像这样的东西

 Sheets("someVeryFunnySheetName").buttons("someSeriousButtonName").onAction = "macroName" 

下面是一个例子,如果你要传递参数给macros(axOutputSHeetCounter是我认为的一些整数)

 With chartSheet.Buttons("closeOutputSheet") .OnAction = "'Module7_Axle.closeOutputSheet """ & axleOutputSheetCounter & """'" .Characters.text = "Delete sheet" .Characters.Font.Size = 16 End With 

编辑:对于这里的 activeXbutton,你可以find同样的问题和工作解决scheme的问题

所以从你自己发布的链接,你的代码将如下所示:

 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 

但这只适用于activeXbutton。 它所做的是相当黑客…所以如果你有一个更好的解决scheme,我不会推荐这一个。 它是这样做的:每个ActiveXbutton都有一个onclick函数,其语法如下:“ButtonName_Click()”如果你在代码中的某处放置了这一行,它将在点击时执行。 现在代码做什么(就像你已经发布的链接一样),是把这些函数写入用户表单代码中。