I want to create an Access form cointaining 50 command buttons and I want to iterate through those buttons. Of course creating buttons by hand (using the tools in the ribbon) is not a solution. I want to create those buttons through a loop using vba code. How I can do that?
Asked
Active
Viewed 3,696 times
-2
-
Please add more details about your problem and your own efforts this far to solve the problem so that people can help you better. Read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – pirho Nov 20 '17 at 12:09
-
If the number of buttons will always be 50 (i.e. there is not logic that creates/drops buttons based on user interaction) I would do it by hand. Yes it is annoying and takes time, but laying-out controls via code can be a pain too. Event handling is also complicated with dynamic controls. – David Rushton Nov 20 '17 at 12:10
-
Possible duplicate of [How to create controls at run time Access VB?](https://stackoverflow.com/questions/31301070/how-to-create-controls-at-run-time-access-vb) – Andre Nov 20 '17 at 12:29
1 Answers
0
To add a form control you need just CreateControl(form.name, typeOfcontrol, ....)
so, the code would be similar to this:
Sub Add50Forms()
Dim db As DAO.Database
Dim frm As Form
Dim newBt As Control
Dim i As Long, j As Long
Set frm = Application.Forms(1)
For i = 0 To 1
For j = 1 To 25
Set newBt = CreateControl(frm.Name, acCommandButton, Left:=100 + 3000 * i, Top:=500 * j)
Set newBt = Nothing
Next j
Next i
End Sub
I have propesed two nested loops for simplicity, but it could be made with one and some fancy expressions for left:= and top:= named arguments. Of course, you would like to add some captions to those codes and so on. Positions of controls, their size and colours are also up to you.

MarcinSzaleniec
- 2,246
- 1
- 7
- 22