将代码分配给dynamic创build的button

我试图得到一个button,我已经dynamic创build一个Excel用户窗体来运行一个叫做transfer的macros,我已经写在我的项目的“模块”部分的Module 1

下面我粘贴了我已经写在代码中的代码,它实际上是在框架中创build了Transfer to Sheetbutton( 我也是dynamic创build的 ),但由于某种原因,当我运行VBA时, 438 error消息说Object doesn't support this property or method

有谁可以告诉我如何解决这个问题?

代码如下:

 Dim framecontrol1 As Control Set workitemframe = Controls.Add("Forms.Frame.1") With workitemframe .Width = 400 .Height = 400 .Top = 160 .Left = 2 .ZOrder (1) .Visible = True End With workitemframe.Caption = "Test" Set framecontrol1 = workitemframe.Controls.Add("Forms.commandbutton.1") With framecontrol1 .Width = 100 .Top = 70 .Left = 10 .ZOrder (1) .Visible = True .Caption = "Transfer to Sheet" End With framecontrol1.OnAction = "transfer" 

这是一个例子。 请修改它以适应您的需求:)

这个例子将创build一个命令button并为其分配代码,这样当它被按下时,它将显示“Hello World”。

将此代码粘贴到命令button的单击事件中,该button将dynamic创build一个新的命令button,并为其分配代码。

 Option Explicit Dim cmdArray() As New Class1 Private Sub CommandButton1_Click() Dim ctl_Command As Control Dim i As Long i = 1 Set ctl_Command = Me.Controls.Add("Forms.CommandButton.1", "CmdXYZ" & i, False) With ctl_Command .Left = 100 .Top = 100 .Width = 255 .Caption = "Click Me " & CStr(i) .Visible = True End With ReDim Preserve cmdArray(1 To i) Set cmdArray(i).CmdEvents = ctl_Command Set ctl_Command = Nothing End Sub 

并将此代码粘贴到类模块中

 Option Explicit Public WithEvents CmdEvents As MSForms.CommandButton Private Sub CmdEvents_Click() MsgBox "Hello Word" End Sub 

快照

在这里输入图像说明在这里输入图像说明

您需要以编程方式将代码添加到UserForm。 我用这个vbax文章中的代码作为参考

下面的代码:

  1. 从普通模块运行
  2. 将该button添加到名为UserForm1的用户窗体
  3. 将此代码添加到用户窗体Click事件

     Private Sub CommandButton1_Click() Call Transfer End Sub 

从正常的模块VBA

  Sub AddToForm() Dim UF As Object Dim frameCOntrol1 As Object Set UF = ActiveWorkbook.VBProject.VBComponents("UserForm1") Set frameCOntrol1 = UF.designer.Controls.Add("Forms.CommandButton.1") With frameCOntrol1 .Width = 100 .Top = 70 .Left = 10 .ZOrder (1) .Visible = True .Caption = "Transfer to Sheet" End With With UF.CodeModule .InsertLines 2, _ "Private Sub " & frameCOntrol1.Name & "_Click()" & Chr(13) & _ "Call Transfer" & Chr(13) & _ "End Sub" End With End Sub