Is it possible to add a button to the worksheet then write code for that button?

Thanks for reading.

You can add a button from the activeX Contols, then write a code for that button in the worksheet module

Sub AddButtonMakeMacro()
    Dim MySht As Worksheet
    Dim MyOle As OLEObject

    Set MySht = ActiveSheet
    MySht.Range("H1").Select
    Set MyOle = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
                                           Left:=237.75, Top:=21, Width:=93, Height:=22.5)

    With MyOle
        .Object.Caption = "Click Me"
        .Name = "myMacro"
    End With

    With ThisWorkbook.VBProject.VBComponents(MySht.CodeName).CodeModule
        .InsertLines .CreateEventProc("Click", MyOle.Name) + 1, _
                     vbTab & "If Range(""A1"").Value > 0 Then " & vbCrLf & _
                     vbTab & vbTab & "Msgbox ""Hi""" & vbCrLf & _
                     vbTab & "End If"

    End With

End Sub
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.