How to create an ActiveX button and add code to it (tell it what sub to run) using vba?

落爺英雄遲暮 提交于 2019-12-11 03:19:01

问题


I'd like to create an ActiveX button in a sheet and assign a code to it (i.e. tell it to what sub to run and that sub already exists).

I can create the button: (recorded)

ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False _
    , DisplayAsIcon:=False, Left:=41395.5882352941, Top:=234.705882352941, _
    Width:=119.117647058824, Height:=39.7058823529412).Select

But I'd like to change the caption and assign a sub to it so when someone clicks the newly created activex button it runs a sub that already lives in a module within the workbook that the button is to be created. Everything happens and lives in ThisWorkbook.

Thanks!

PS - I cannot use a Command button....I can only use ActiveX


回答1:


This works:

Sub AddingButtons()

Dim btn As Button
Dim t As Range
Dim Obj As Object
Dim Code As String

Dim ShtNm As String
With ThisWorkbook
    .Worksheets.Add(After:=Worksheets(1)).Name = "My New Worksheet"
    .Sheets("My New Worksheet").Activate
End With

ShtNm = ActiveSheet.Name
Sheets(ShtNm).Select

Set t = ActiveSheet.Range("D3:F4")

'create button
Set Obj = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
       Link:=False, DisplayAsIcon:=False, Left:=t.Left, Top:=t.Top, Width:=t.Width, Height:=t.Height)

'button text
ActiveSheet.OLEObjects(1).Object.Caption = "Show Data Selection Window"

'macro text
Code = "Private Sub CommandButton1_Click()" & vbCrLf
Code = Code & "Call MyTestSub(ShtNm)" & vbCrLf
Code = Code & "End Sub"

MsgBox "Worksheet name is " & ActiveSheet.Name
'add macro at the end of the sheet module
With ActiveWorkbook.VBProject.VBComponents(Worksheets(ShtNm).CodeName).CodeModule
    .insertlines .CountOfLines + 1, Code
End With

End Sub

Adapted from: http://social.msdn.microsoft.com/Forums/office/en-US/1a48cdfd-42af-486c-a4a5-3d5d5797d00c/adding-an-active-x-command-button-and-its-code-using-in-excel-vba?forum=exceldev

PS - Tim - had the answer in his comment on my original question. Thx tim. How to create a dynamic button in excel




回答2:


For Excel 2013 click Developer/Insert/ActiveX Command Button. After insertion, right click the button, choose properties for caption and other manipulations, choose view code for macro assignment.



来源:https://stackoverflow.com/questions/23299301/how-to-create-an-activex-button-and-add-code-to-it-tell-it-what-sub-to-run-usi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!