(Solved) – VBA Excel array of control ComandButtons to create a full panel from code


I have been doing these days of quarantine a game for playing Sink The Fleet human vs the program I made. I have near 5000 lines of code in the user form. I have 200 buttons and I have copied and pasted the same code for all the buttons (1 day of bored work changing some part of the name).

What I would like to do for the next time is to create an array of buttons to program all the buttons with a for loop. I can define a matrix of command buttons then I build the buttons in this way

Set Button(j, i) = UserForm2.Controls.Add("Forms.CommandButton.1") 

and the buttons appear on the userform but I can not call to commandbuttons_click in the code because the button doesn’t exist in memory before I run the user form.

Does anyone know a way to do it? Or a way to call a function when I push the button?

Leave a Reply

Your email address will not be published. Required fields are marked *