1

我有一个在运行时创建命令按钮的模块。它将以指定的用户表单创建命令按钮。当我执行模块时,程序运行良好。

但是,当我使用用户表单来调用模块时,出现错误说明

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

好心提醒。

4

1 回答 1

2

编辑后的帖子:基于 VBProject 表单组件

较早的帖子适用于 Excel 工作表按钮。我注意到您可以caption通过直接引用button自身来设置表单按钮。我试过你的代码。似乎没有发现任何错误。我做的唯一额外的事情是添加引用库 ( MS VB Extensibility 5.3)、Private代码范围并将代码组合到一个with语句中。

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

修改后的代码:

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 工作表按钮打开新创建的带有按钮的表单。

在此处输入图像描述


初始帖子:

请查看这篇文章以供参考:Excel VBA 在单元格旁边创建一个按钮

  • 由于( 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
于 2013-01-01T09:31:27.253 回答