VBA Excel 2010 - 如何将宏指定给使用宏创建的命令按钮

时间:2016-04-14 11:39:23

标签: excel vba excel-vba macros

我有一个创建命令按钮的宏但是我无法将任何宏指定给VBA中的按钮

查看了this链接,但是它是用户形式的(但我不够好,无法根据我的需要进行更改)

我目前正在考虑的代码如下,我猜我需要在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

2 个答案:

答案 0 :(得分:3)

因此,根据您发布的链接,您的代码将如下所示:

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按钮都有一个带有以下语法的onclick函数:" ButtonName_Click()"如果您在代码中的某个位置放置此行,则会在单击时执行。现在代码的作用(如你发布的链接),它是将这些函数写入userform代码。

答案 1 :(得分:2)

使用.onAction方法

像这样的东西

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

这是一个例子,如果你想将参数传递给那个宏(我认为的是axisOutputSHeetCounter是一个整数)

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

编辑:对于activeX按钮here,您可以找到具有相同问题和工作解决方案的问题