在运行时创建命令按钮时出错

时间:2013-01-01 08:33:13

标签: vba excel-vba excel

我有一个在运行时创建命令按钮的模块。它将以指定的用户形式创建命令按钮。执行模块时,程序运行正常。

但是,当我使用用户表单来调用模块时,我有一个错误说明

Run-time error '91': Object variable or With block variable not set

代码

 Sub AddButtonAndShow()

    Dim Butn As CommandButton
    Dim Line As Long
    Dim objForm As Object
    Dim i As Integer
    Dim x As Integer

    Set objForm = ThisWorkbook.VBProject.VBComponents("Current_Stock")



For i = 1 To 3
    Set Butn = objForm.Designer.Controls.Add("Forms.CommandButton.1")
    With Butn
        .Name = "CommandButton" & i
        .Caption = i
        .Width = 100
        .Left = 300
        .Top = 10 * i * 2
    End With
Next

    For x = 1 To 3
        With objForm.CodeModule
            Line = .CountOfLines
            .InsertLines Line + 1, "Sub CommandButton" & x & "_Click()"
            .InsertLines Line + 2, "MsgBox ""Hello!"""
            .InsertLines Line + 3, "End Sub"
      End With
    '
     Next x

End Sub

请告知。

1 个答案:

答案 0 :(得分:2)

编辑后:基于VBProject表单组件

之前的帖子是Excel Sheet按钮。我注意到对于表单按钮,您可以通过直接引用caption本身来设置button。我试过你的代码。似乎没有发现任何错误。我做的唯一的附加功能是添加参考库(MS VB Extensibility 5.3),Private范围来编码并将代码组合成一个with语句。

根据 Mr.Excel article ,您需要在VB编辑器关闭时添加 do Events 来运行代码。您的错误似乎与文章中提到的内容非常相似。

修订代码:

Sub AddButtonAndShow()

    Dim Butn As CommandButton
    Dim Line As Long
    Dim objForm As Object
    Dim i As Integer
    Dim x As Integer
    Dim code As String

        Application.DisplayAlerts = False
        DoEvents
        On Error Resume Next
        Set objForm = ActiveWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm)
        objForm.Name = "thisform1"

        For i = 1 To 3
            Set Butn = objForm.Designer.Controls.Add("Forms.CommandButton.1")
            With Butn
                    .Name = "CommandButton" & i
                    .Caption = i
                    .Width = 100
                    .Left = 100
                    .Top = (i * 24) + 10

                    Line = objForm.CodeModule.CountOfLines + 1
                    code = "Private Sub " & Butn.Name & "_Click()" & vbCr
                    code = code & "MsgBox ""Hello!""" & vbCr
                    code = code & "End Sub"
                    objForm.CodeModule.InsertLines Line, code
              End With
        Next
        Application.DisplayAlerts = False
   VBA.UserForms.Add(objForm.Name).Show
End Sub

Excel命令按钮代码:

Private Sub CommandButton3_Click()
Call AddButtonAndShow
End Sub

输出:使用Excel工作表按钮用按钮打开新创建的表单。

enter image description here


首发帖子:

请查看此帖子以供参考:Excel VBA create a button beside cell

  • object doesn't support property or method引起的可能错误属于Caption属性。因为必须使用 theBttn.Object.Caption
  • 进行设置

请试试这个:

With Butn
  .Name = "CommandButton" & i
  .Object.Caption = i
  .Width = 100
  .Left = 300
  .Top = 10 * i * 2
End With