以编程方式在VBA Userform中生成按钮

时间:2017-03-24 03:39:29

标签: excel vba excel-vba

我正在编写VBA以在用户窗体中以编程方式生成按钮。但是我已成功在userform中创建一个按钮,并为按钮单击事件添加代码,但该按钮不会在commandbutton_click()下运行代码。有人可以帮我调试我的代码吗?

错误发生在"设置NewCommandButton1 = MyUserForm.Desinger.Controls.Add(" forms.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

1 个答案:

答案 0 :(得分:1)

我使用此代码创建控件。

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,这可能是默认设置,也是我的代码甚至没有它的原因。