0

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

1 Answer 1

2

I use this code to create controls.

Private Function CreateControl(ByVal Ctype As String, ByVal Cname As String, ByVal Cwidth As Single, ByVal Cheight As Single, ByVal Ctop As Single, ByVal Cleft As Single) As MSForms.Control
    ' 014.8013.1.0
    Set CreateControl = Controls.Add("Forms." & Ctype & ".1")
    With CreateControl
    If Len(Cname) Then .Name = Cname
    .Width = Cwidth
    .Height = Cheight
    .Top = Ctop
    .Left = Cleft
    End With
End Function

Note that the Ctype argument could be "Commandbutton". The difference with your code seems to be in the dimensioning. you have Dim NewCommandButton1 As MSForms.CommandButton whereas I use Dim NewCommandButton1 As MSForms.Control. Another is in the specification of Desinger in the Add method. I think this is from VB, not VBA, and mis-spelled as well. Your code is ambiguous about MyUserForm. By nature, this should be Me which is likely the default and why my code doesn't even have it.

Sign up to request clarification or add additional context in comments.

1 Comment

Great! Glad to be of help. Please accept the answer, then. (It's that green checkmark below the ratings)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.