0

I created a Userform, that shows a few values from the table (within textboxes) that can be edited and a command button to save those changes back into the table.

Since I use the same template for various values I decided to dynamically create the Userform at runtime. But I can't get the command button to work at all. I cross-checked with various examples (on StackOverflow and other sites, e.g. here and here), but I can't find the problem.

This is my (simplified) code. The procedure is being called by a button click event itself (CommandButton1). As a workaround, I created a static (empty) UserForm UserForm1 which I use as a starting point to create a specific configuration of the form dynamically during runtime. Essentially it means that just the form elements are created dynamically. At least for now, but that's fine since I only need one single instance of the form to be displayed at any given time. Eventually, I would like to create the form at runtime too:

Private Sub CommandButton1_Click()
  'Set Form
    UserForm1.Caption = "Test"
  'Create Form-Elements (Commandbutton)
    Dim cmdButton01 As MSForms.CommandButton
    Set cmdButton01 = UserForm1.Controls.Add("Forms.CommandButton.1", "dynCmdButton01")
    cmdButton01.Width = 50
    cmdButton01.Caption = "Save"
  'Show Form
    UserForm1.Show
  End Sub

Private Sub dynCmdButton01_click()
  MsgBox "Test"
  End Sub
4
  • 1
    Does this answer your question? Assign code to a button created dynamically Commented Aug 19, 2020 at 11:19
  • @TomBrunberg the missing class module was the problem, not sure if you or TJS was first to answer but feel free to add one if you like. Commented Aug 19, 2020 at 17:03
  • I support that you assign @TJS 's answer as the correct one. Cheers Commented Aug 19, 2020 at 17:05
  • @TomBrunberg I will, thank you again... Commented Aug 19, 2020 at 17:06

1 Answer 1

2

You should create a class module and assign the event through it:

Sign up to request clarification or add additional context in comments.

1 Comment

the missing class module was the problem, not sure if you or Tom was first to answer?!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.