Bonjour,
Un exemple pour un CommandButton avec un début de code associé.
A étudier.
Cdlt.
Option Explicit
'Option Private Module
'https://msdn.microsoft.com/fr-fr/library/office/ff195728.aspx
Public Sub CreateCommandButton()
Dim cmd As OLEObject
Dim Acell As Range
Dim Message As String, Title As String, strText As String, strText2 As String
Dim Code As String
Dim NextLine As Long
Message = "Donnez un nom au bouton."
Title = "Nom bouton ?"
strText = InputBox(Message, Title)
If strText = "" Then Exit Sub
Application.ScreenUpdating = False
Set Acell = ActiveCell
strText2 = WorksheetFunction.Proper(Replace(Replace(strText, " ", "_"), "-", "_"))
Set cmd = ActiveSheet.OLEObjects.Add _
(ClassType:="Forms.CommandButton.1", _
Link:=False, _
DisplayAsIcon:=False, _
Left:=Acell.Left, _
Top:=Acell.Top, _
Width:=100, _
Height:=35)
With cmd
.Name = "cmd" & strText2
.PrintObject = False
With .Object
.AutoSize = True
.BackColor = RGB(54, 96, 146)
.Caption = strText
.Font.Bold = True
.ForeColor = RGB(255, 255, 255)
.TakeFocusOnClick = False
End With
End With
Code = "Private Sub " & cmd.Name & "_Click()" & vbCrLf
Code = Code & "'" & vbCrLf
Code = Code & "End Sub"
On Error Resume Next
With ActiveWorkbook.VBProject.VBComponents(ActiveSheet.CodeName).CodeModule
NextLine = .CountOfLines + 1
.insertlines NextLine, Code
End With
If err.Number <> 0 Then
MsgBox "Erreur : " & err.Number & vbLf & err.Description
err.Clear
End If
Set cmd = Nothing
Set Acell = Nothing
End Sub