运行时' 13'错误尝试以编程方式创建用户窗体按钮时类型不匹配

时间:2015-09-24 15:40:02

标签: excel vba

Private Sub UserForm_Initialize()
 Dim cCont As Control

Set cCont = Me.Controls.Add _
        ("Forms.CommandButton.1", "CopyOf")

    With cCont
        .Caption = "Thanks for creating me"
        .AutoSize = True
    End With

End Sub

以上代码给出了运行时错误' 13"类型不匹配错误

但是,如果我这样做:

Private Sub UserForm_Initialize()
 Me.Controls.Add _
        "Forms.CommandButton.1", "CopyOf"
end sub

创建命令按钮时没有错误。我想创建几个命令按钮,因此,我希望上面的第一段代码能够工作。我怎么能这样做?

这是在Excel 2010,Windows 7 x64

1 个答案:

答案 0 :(得分:1)

看看这个:

#get_object

此外,如果您真的想使用对象变量,那么您最好使用特定类型:

Private Sub UserForm_Initialize()

    With Controls.Add("Forms.CommandButton.1", "CopyOf")
        .Caption = "Thanks for creating me"
        .AutoSize = True
    End With

    With Controls.Add("Forms.CommandButton.1", "cmd2nd")
        .Top = 25
        .Caption = "Me too..."
        .AutoSize = True
    End With

End Sub