简体   繁体   中英

VBA Excel 2010 - How to assign a macro to a command button that was made with a macro

I have a macro that creates a command button however I am unable to assign any macro to the button in the VBA

have looked at this link but its for a userform (but I'm not good enough to be able to change it to suit what I need)

The code I am currently tring is below, I'm guessing I need to add something to the With Statement but I dont know what it would be

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

So from your own link you have posted, your code would look like this:

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

But this only works with activeX Buttons. What it does is quite a hack... so if you have a better solution i would not recommend this one. What it does is this: Every ActiveX Button has a onclick function with the following Syntax: "ButtonName_Click()" If you somewhere in your code put this line, it will be executed on click. now what the code does (as in the link which you have posted), is it writes These functions into the userform code.

Use .onAction method

Something like this

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

Here is one example, if you wana to pass parameter to that macro (axleOutputSHeetCounter is some integer i think)

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

edit: for activeX buttons here you can find question with same issue and working solution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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