I am trying to create a variable number of controls (combo boxes) in an excel userform based on the number of columns that are on a particular worksheet being viewed. Ideally I would like to delete and existing ones and create new ones at run-time, rather than creating 100 or so and just toggling back and forth between visible and invisible. What I have at the moment will create a combo box and loop, but it only creates 1. It looks as though the combo box is being overwritten and ends with the last combo box created. Any suggestions to get all onto the same userform at run-time?
Private Sub CommandButton1_Click()
Dim cCont As New Control
Dim ws As Worksheet
Dim lc As Long
Dim i As Long
Set ws = Loan_Data
lc = Loan_Data.Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To lc
Set cCont = Me.Controls.Add("Forms.CommandButton.1", "NewCombo" & i)
With cCont
.Caption = cCont.Name
.AutoSize = True
.Visible = True
End With
Next i
End Sub
With a little bit of math you can get that totally dynamic. Use a frame where you place the controls. Now you have coordinates relative to the frame. Use an "y_offset" and a "lineheight" variable and/or a "x_offset" and a "linewidth" variable and create controls with calculated positions (top and left). During the creation count the offset + (lines*lineheight) and set the Frames ScrollHeight (and/or ScrollWidth) according to the result...
Did that sometimes. Works very well.
I can share with you an example of a Procedure I used to create some ComboBoxes at Run time.
Hope it helps.