Search code examples
excelvbaactivex

How to rename a newly created ActiveX button?


Per Mathieu's reply, I managed to create an ActiveX button via

Sub aaaaaaaa()
Dim newButton As Object
Set newButton = Sheets(sheetname_KvE).OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
    Link:=False, _
    DisplayAsIcon:=False, _
    Left:=800, _
    Top:=0, _
    Width:=300, _
    Height:=30).Object
With newButton
    .Caption = "bla"
    '.Name = "Button_what" ' - THIS DOES NOT WORK!
End With
End Sub

How can I rename that button?

Unfortunately, these links did not lead me to the solution:

This would be quite glorious, as it enables one to add relevant code in the sheet's module (as far as I can see, they relevant sub is always called [insert button name]_Click).


Solution

  • Is this what you are trying?

    Sub Sample()
        Dim newButton As OLEObject
        Dim ws As Worksheet
        
        Set ws = Sheets(sheetname_KvE)
        Set newButton = ws.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
                                          Link:=False, _
                                          DisplayAsIcon:=False, _
                                          Left:=800, _
                                          Top:=0, _
                                          Width:=300, _
                                          Height:=30)
        newButton.Object.Caption = "bla"
        newButton.Name = "Button_what"
    End Sub