I found some vba code on the internet that dynamically creates a number of textboxes with a commandbutton click. For this a textbox and the button is allready placed on the Userform. I did create a second button that would repeat the proces (dynamically create a number of textboxes) but this button needs to get the value out of the dynamically, first, created textbox. Somehow I do not manage to call this textbox with my button click event. Can someone please help me out. Thank u so much
Private Sub cmdAddBoxes_Click()
Dim idx As Long
Dim maxBoxes As Long
Dim x As Long, y As Long
Dim ctl As Control
Dim newBox As MSForms.TextBox
maxBoxes = Val(txtNumBoxes.Text)
If (maxBoxes > 0) And (maxBoxes <= 1) Then
' remove any existing boxes
For Each ctl In Me.Controls
If Len(ctl.Tag) > 2 Then
If Left(ctl.Tag, 3) = "new" Then
Controls.Remove (ctl.Name)
End If
End If
Next
For idx = 1 To maxBoxes
Set newBox = Me.Controls.Add("Forms.TextBox.1")
With newBox
.Tag = "new" & .Name
.BackColor = &HC0FFFF
.Value = 1
'MsgBox "new" & .Name
'MsgBox .Value
' make two columns of boxes
If idx < 6 Then
.Left = 12
.Width = 78
.Height = 18
.Top = 16 + 24 * idx
Else
.Left = 100
.Top = 16 + 24 * (idx - 5)
End If
End With
Next
Else
MsgBox "Number must be 1 to 1"
End If
txtNumBoxes.Text = ""
Label2.Visible = True
End Sub
Private Sub cmdAddBoxes1_Click()
Dim idx As Long
Dim maxBoxes As Long
Dim x As Long, y As Long
Dim ctl As Control
Dim newBox As MSForms.TextBox
maxBoxes = Val(NewTextBox1.Text)
If (maxBoxes > 0) And (maxBoxes <= 1) Then
' remove any existing boxes
For Each ctl In Me.Controls
If Len(ctl.Tag) > 2 Then
If Left(ctl.Tag, 3) = "new" Then
Controls.Remove (ctl.Name)
End If
End If
Next
For idx = 1 To maxBoxes
Set newBox = Me.Controls.Add("Forms.TextBox.1")
With newBox
.Tag = "new" & .Name
.BackColor = &HC0FFC0
.Text = 1
'MsgBox "new" & .Name
' make two columns of boxes
If idx < 6 Then
.Left = 12
.Width = 78
.Height = 18
.Top = 16 + 24 * idx
Else
.Left = 100
.Top = 16 + 24 * (idx - 5)
End If
End With
Next
Else
MsgBox "Number must be 1 to 1"
End If
NewTextBox1.Text = ""
End Sub
txtNumBoxesvsNewTextBox1(so, which one is it, we cannot know nor should we guess) (3) a different background color&HC0FFFFvs&HC0FFC0(4) using the.Valueor the.Textproperty to change the value. So, none of these changes really matter too much and don't require a double-post of the same code snippet.TextBoxes(during run-time). If that's the case then you should name your controls when you generate them. At the moment you are not naming them when you are adding them. To name them please have a look at this question / answer: stackoverflow.com/questions/10544456/… Note, that the names are automatically increased by a number to ensure no conflicting names.NewTextBox1you'll have to useMe.Controls("NewTextBox1").Valueas indicated here: stackoverflow.com/questions/24083717/…