Reputation: 11
I have one question about how to read a text from dynamically added TextBox. In my UserForm I have one TextBox and in this TextBox I put a number of how much new TextBoxes I want add. From this one TextBox I add two new dynamic TextBox.
Set Ctrl = .Add("Forms.TextBox.1", Window.Name + CStr(i)) 'TextBox for code
With Ctrl
.Width = 32
.Height = 16
.Top = TopPos
.Left = 6
.Value = Chr(64 + i) + CStr(10 + i)
.MaxLength = 4
.ZOrder (0)
End With
Set Ctrl = .Add("Forms.TextBox.1", Window.Name + CStr(i)) 'TextBox for comment
With Ctrl
.Width = 240
.Height = 16
.Top = TopPos
.Left = 44
.MaxLength = 50
.ZOrder (0)
End With
First column of TextBoxes is filling automatically with a letter and a number, a second column is empty for my comments. With Finish button I want to export text from both TextBoxes to a two cells - text from first column of TextBoxes to a cell "A" and text from second column of TextBoxes to a cell "B" in new file. I wrote a function to find a text in each of new TextBoxes:
Function FindName(Iter As Integer, Name As String) As String
Dim Text As String
Dim Ctrl As Control
For Each Ctrl In UserForm1.Controls
If Ctrl.Name = Name Then
Text = Ctrl.Text
End If
Next Ctrl
FindName = Text
End Function
I use this function to fill up a new Excel with text from TextBoxes, but the problem is, that a text is exported only from the second column to a new file:
NewFile.Worksheets(1).Cells(StartValue + i, 1) = FindName(i, "TextBox1" + CStr(i))
NewFile.Worksheets(1).Cells(StartValue + i, 2) = FindName(i, "TextBox1" + CStr(i))
Is there any solution how to distinguish the text from first column of TextBoxes and from second column of TextBoxes to export a text from first TextBox to one cell and from second TextBox to another cell?
Thank you for the help.
Upvotes: 0
Views: 111
Reputation: 29612
As you retrieve the controls by name, you need to give them unique name. This is done with the second parameter of the .Add
-command. In your code, you give the controls for code and comment the same name and therefore the FindName
-function can find only one of them. Have a look to the following code - it creates TextBoxes with names like tbCode_1
and tbComment_1
- change it to your personal taste if you don't like it.
Set Ctrl = .Add("Forms.TextBox.1", "tbCode_" & CStr(i)) 'TextBox for code
(...)
Set Ctrl = .Add("Forms.TextBox.1", "tbComment_" & CStr(i)) 'TextBox for comment
Your FindName
-function could look like
Function FindName(Iter As Integer, colName As String) As String
Dim ctrlName as String
ctrlName = "tb" & colName & "_" & CStr(i)
On Error Resume Next
FindName = Me.Controls(ctrlName).Text
On Error Goto 0
End Function
and you call it with
NewFile.Worksheets(1).Cells(StartValue + i, 1) = FindName(i, "Code")
NewFile.Worksheets(1).Cells(StartValue + i, 2) = FindName(i, "Comment")
Upvotes: 1