将代码分配给动态创建的按钮

时间:2012-04-19 08:41:12

标签: excel vba excel-vba

我正在尝试获取一个我在excel userform表单上动态创建的按钮来运行一个名为transfer的宏,我在Module 1的“模块”部分写了这个项目

下面我已经将我迄今为止编写的代码粘贴到userform中,该用户窗体实际上设法在框架中创建Transfer to Sheet按钮(我也动态创建)但出于某种原因,当我运行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"

2 个答案:

答案 0 :(得分:23)

这是一个例子。请根据您的需要进行修改:)

此示例将创建一个命令按钮并为其分配代码,以便在按下该按钮时,它将显示“Hello World”。

将此代码粘贴到命令按钮的单击事件中,该按钮将动态创建新的命令按钮并为其分配代码。

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

<强>快照

enter image description here enter image description here

答案 1 :(得分:9)

您需要以编程方式将代码添加到UserForm。我使用此vbax article中的代码作为参考

以下代码:

  1. 从正常模块运行
  2. 将按钮添加到名为 UserForm1
  3. 的UserForm中
  4. 将此代码添加到Clickform的Userform

    Private Sub CommandButton1_Click()
    Call Transfer
    End Sub
    
  5. 来自普通模块的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