'créer un userform et controls par code
'cocher ref: Microsoft forms 2.0 Object Library
Sub UserForm_CreatForms()
Dim UF As Object
Dim L As MSForms.Label
Dim CB As MSForms.CommandButton
Dim A$
Dim I&
On Error GoTo Fin
'---- Crée dynamiquement un UserForm ----
Set UF = ThisWorkbook.VBProject.VBComponents.Add(3)
With UF
.Properties("Caption") = "UserForm à la volée"
.Properties("Height") = 240
.Properties("Width") = 320
End With
'---- Crée le bouton de fermeture ----
Set CB = UF.Designer.Controls.Add("forms.CommandButton.1")
With CB
.Caption = "Fermer"
.Left = 200
.Top = 180
End With
'---- Crée le label ----
Set L = UF.Designer.Controls.Add("forms.Label.1")
With L
.Caption = "mon texte"
.TextAlign = fmTextAlignCenter
.Left = 20
.Top = 20
.BackColor = vbRed
.BorderStyle = fmBorderStyleSingle
End With
'°°° Ajout du code évènementiel °°°
A$ = "Sub CommandButton1_Click()" & vbCrLf & "Unload Me" & vbCrLf & "End Sub"
With UF.CodeModule: I& = .CountOfLines: .InsertLines I& + 1, A$: End With
'-----------
A$ = "Sub Label1_Click()" & _
vbCrLf & "MsgBox " & """Vous avez cliqué sur mon texte""" & vbCrLf & "End Sub"
With UF.CodeModule: I& = .CountOfLines: .InsertLines I& + 1, A$: End With
'---- Affiche le UserForm ----
VBA.UserForms.Add(UF.Name).Show
'---- Détruit le UserForm ----
ThisWorkbook.VBProject.VBComponents.Remove UF ' <<<<<<<<<<< supprime l'userf
Fin:
End Sub