以编程方式在VBA用户窗体中生成按钮

以编程方式在VBA用户窗体中生成按钮,vba,excel,Vba,Excel,我正在编写一个VBA,以编程方式在userform中生成一个按钮。但是,我已经成功地在userform中创建了一个按钮,并为button click事件放置了代码,但是该按钮没有在commandbutton\u click下运行代码。有人能帮我调试代码吗 Set-NewCommandButton1=MyUserForm.Desinger.Controls.Addforms.CommandButton.1出现错误,错误代码为对象变量或块变量未设置错误91 万分感谢 Option Explicit

我正在编写一个VBA,以编程方式在userform中生成一个按钮。但是,我已经成功地在userform中创建了一个按钮,并为button click事件放置了代码,但是该按钮没有在commandbutton\u click下运行代码。有人能帮我调试代码吗

Set-NewCommandButton1=MyUserForm.Desinger.Controls.Addforms.CommandButton.1出现错误,错误代码为对象变量或块变量未设置错误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

我使用此代码创建控件

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用作MSForms.CommandButton,而我将Dim NewCommandButton1用作MSForms.Control。另一个是在规范中对Desinger中的Add方法进行说明。我认为这是来自VB,而不是VBA,而且拼写错误。您的代码对MyUserForm不明确。从本质上说,这应该是我,这可能是默认的,为什么我的代码甚至没有它。

太好了!很高兴能帮上忙。那么请接受答案。是评级下面的绿色复选标记