以编程方式将命令按钮添加到用户窗体

时间:2009-12-16 21:35:17

标签: excel vba excel-vba

在excel vba中,我向userform添加了一个命令按钮...如下所示

      Set ctrl = Me.Controls.Add( _
      bstrProgID:="Forms.CommandButton.1", _
      Name:="CommandButton1", Visible:=True)

现在我想知道如何点击它时该怎么做?谢谢!

1 个答案:

答案 0 :(得分:6)

这是vba将你做的那些技巧之一,但你可能不应该这样做。出于同样的原因,您不应该使用改变代码的代码。

那就是说,这是你想做的事情。首先插入一个类模块并将其命名为DynBtn,然后将此代码粘贴到其中:

Private WithEvents mobjBtn As MSForms.CommandButton
Private msOnAction As String
''// This has to be generic or call by name won't be able to find the methods
''// in your form.
Private mobjParent As Object

Public Property Get Object() As MSForms.CommandButton
    Set Object = mobjBtn
End Property

Public Function Load(ByVal parentFormName As Object, ByVal btn As MSForms.CommandButton, ByVal procedure As String) As DynBtn
    Set mobjParent = parentFormName
    Set mobjBtn = btn
    msOnAction = procedure
    Set Load = Me
End Function

Private Sub Class_Terminate()
    Set mobjParent = Nothing
    Set mobjBtn = Nothing
End Sub

Private Sub mobjBtn_Click()
    CallByName mobjParent, msOnAction, VbMethod
End Sub

现在要在表单中使用它,创建一个空白用户表单并将此代码粘贴到其中:

Private Const mcsCmdBtn As String = "Forms.CommandButton.1"
Private mBtn() As DynBtn

Private Sub UserForm_Initialize()
    Dim i As Long
    ReDim mBtn(1) As DynBtn
    For i = 0 To UBound(mBtn)
        Set mBtn(i) = New DynBtn
    Next
    ''// One Liner
    mBtn(0).Load(Me, Me.Controls.Add(mcsCmdBtn, "Btn1", True), "DoSomething").Object.Caption = "Test 1"
    ''// Or using with block.
    With mBtn(1).Load(Me, Me.Controls.Add(mcsCmdBtn, "Btn2", True), "DoSomethingElse").Object
        .Caption = "Test 2"
        .Top = .Height + 10
    End With
End Sub

Public Sub DoSomething()
    MsgBox "It Worked!"
End Sub

Public Sub DoSomethingElse()
    MsgBox "Yay!"
End Sub

Private Sub UserForm_Terminate()
    Erase mBtn
End Sub