Programmatically adding a command line to a custom form

In excel vba I added userform ... command as below

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

Now I wanted to know how I can say what to do when I click? thanks!!

+3
source share
1 answer

This is one of those methods that vba will allow you to do, but you probably shouldn't. For all the same reasons, you should not use code that modifies your code.

So here is how to do what you want. First insert the 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 an empty 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
+6
source

Source: https://habr.com/ru/post/1725898/


All Articles