Search code examples
vbaeventsruntimeuserform

Use VBA to create a dynamic form with a button using "vbModeless"


I want to create a vbModeless dynamic user form during run-time. The user form has just one button, that's it. The form works fine using vbModal but unfortunately with vbModeless I can't get the click event for the button to work. Clicking the button does not call the event. I'm using the following steps/code:

  • Created an empty user form named UserForm1

  • Created a module named Modul1 with the following code:

    Sub CreateFormControls()
    
      'Create Command Button
      Dim Button01 As MSForms.CommandButton
      Set Button01 = UserForm1.Controls.Add("Forms.CommandButton.1", "dynButton01", False)
      Button01.Visible = True
    
      'Reference click event
      Dim ClickEvents As New Class1
      Set ClickEvents.ButtonEvent = Button01
    
      'Show User Form
      UserForm1.Show vbModeless '-> THIS DOES NOT WORK, only vbmodal works
    
    End Sub
    
  • Created a class module named Class1 with the following code:

     Public WithEvents ButtonEvent As MSForms.CommandButton
    
     Private Sub ButtonEvent_Click()
         MsgBox "Test"
         Unload UserForm1
     End Sub
    

Is there a way to get this working with vbModeless or is there a different work around?

Note: I haven't used dynamic forms very much yet, and I copied/modified the shown implementation using an existing code snippet without completely understanding how the button object references the click event e.g. why a separate class is needed and I can't do it within the procedure in Modul1. I assume within lies the reason why it doesn't work opening the form non-modal. A little light on this issue would be appreciated as well.


Solution

  • ClickEvents should be declared at the module level...

    Option Explicit
    
    Dim ClickEvents As New Class1 'declared at the module level
    
    Sub CreateFormControls()
    
      'etc
      '
      '
    
    End Sub