views:

1213

answers:

1

hi, in excel vba i have added a commandbutton to userform... like below

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

Now I wanted to know how would I tell it what to do when it is clicked? thanks!!

+1  A: 

Hi asel, This is one of those techniques that vba will let you do, but you probably shouldn't. For all the same reasons you shouldn't use code that alters your code.

That said, here is how to do what you want. First insert a class module and name it DynBtn, then paste this code into it:

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

Now to use this in your form, create a blank user form and paste this code into it:

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
Oorang