21

我正在尝试获取我在 excel 用户窗体表单上动态创建的按钮,以运行transfer我在Module 1项目的“模块”部分中编写的宏。

下面我粘贴了到目前为止我在用户窗体中编写的代码,它实际上设法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"
4

2 回答 2

25

这是一个例子。请修改它以满足您的需要:)

此示例将创建一个命令按钮并为其分配代码,以便在按下它时显示“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

快照

在此处输入图像描述 在此处输入图像描述

于 2012-04-19T09:13:25.293 回答
9

您需要以编程方式将代码添加到用户窗体。我使用这篇vbax 文章中的代码作为参考

下面的代码:

  1. 从普通模块运行
  2. 将按钮添加到名为UserForm1的用户窗体
  3. 将此代码添加到单击事件的用户窗体中

    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
于 2012-04-19T11:14:34.553 回答