以编程方式生成VBA用户窗体中的button

我正在写一个VBA以编程方式在用户窗体中生成一个button。 不过,我已经成功地在用户窗体中创build一个button,并且将button单击事件的代码,但button不运行commandbutton_click()下的代码。 任何人都可以帮我debugging我的代码?

“Set NewCommandButton1 = MyUserForm.Desinger.Controls.Add(”forms.CommandButton.1“)”错误代码为“Object variable or With block variable not set(Error 91)”时出错

万分感谢

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 

我使用这个代码来创build控件。

 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 

请注意,Ctype参数可以是“Commandbutton”。 与您的代码的差异似乎在尺寸。 你有Dim NewCommandButton1 As MSForms.CommandButton而我使用Dim NewCommandButton1 As MSForms.Control 。 另一种是在Add方法中的Desinger的规范中。 我认为这是从VB,而不是VBA,拼写错误。 你的代码对于MyUserForm是不明确的。 本质上,这应该是Me可能是默认的,为什么我的代码甚至没有它。