I am writing a VBA to generate a button programmatically in a userform. However I have successfully to create a button in the userform and also put codes for the button click event, but the button doesn't run the code under the commandbutton_click(). Would anyone can help me to debug my codes?
An error is ocurring at "Set NewCommandButton1 = MyUserForm.Desinger.Controls.Add("forms.CommandButton.1")" with the error code of "Object variable or With block variable not set (Error 91)"
Million thanks
Option Explicit
Private Sub UserForm_Initialize()
Dim X As Long
Dim MyUserForm As Object
Dim NewCommandButton1 As MSForms.CommandButton
Set MyUserForm = ActiveWorkbook.VBProject.VBComponents("UserForm3")
Set NewCommandButton1 = MyUserForm.Desinger.Controls.Add("forms.CommandButton.1")
With NewCommandButton1
.Caption = "Welcome"
.Height = 18
.Width = 44
.Left = 147
.Top = 6
End With
With MyUserForm.CodeModule
X = .CountOfLines
.InsertLines X + 1, "Sub CommandButton1_Click()"
.InsertLines X + 2, " MsgBox ""Hello"""
.InsertLines X + 3, "End Sub"
End With