-
Listbox to textbox
I'm trying to pull all the items from a listbox on form 1 and put them into a multiline textbox on form 2
This is the code I have but it doesn't work:
Dim i As Integer
i = 0
For i = Form1.ListEmail.ListCount - 1 To 0 Step -1
Form1.ListEmail.Text = Me.txtRecipients.Text
Next
Any ideas???
-
Re: Listbox to textbox
Code:
Dim i As Long
Dim strText As String
With Form1.ListEmail
For i = .ListCount - 1 To 0 Step -1
strText = strText & .List(i) & vbNewLine
Next
End With
Me.txtRecipients.Text = strText
-
Re: Listbox to textbox
or even easier:
Code:
For i = 0 To ListEmail.ListCount
Form1.txtRecipients.Text = Form1.txtRecipients.Text & ListEmail.List(i) & vbNewLine
Next
-
Re: Listbox to textbox
Ellis Dee's code reverses the order, which might not be what you intended. Simply loop from 0 to .ListCount - 1 to keep the list in the same order, or use this alternative.
Code:
Dim i As Long
Dim strText() As String
With Form1.ListEmail
ReDim strText(.ListCount - 1)
For i = 0 To .ListCount - 1
strText(i) = .List(i)
Next i
End With
Me.txtRecipients.Text = Join(strText, vbNewLine)
Mxjerrett, that may be easier, but it is inefficient. Using the With block speed access to the List, and using a temporary string variable is faster than using the Text property of the textbox.
-
Re: Listbox to textbox
She reverses the order in the OP, so I went with that. You may be right that that's not what she intended.
Based on the string optimization threads we've had lately, I had to fight the urge to go ulta-optimized. I almost started out by counting the length of each item, creating a string of the total length, etc... I didn't want to obscure the solution too much, but the one-liner approach is just too inefficient for me to feel good about offering.
Your solution gives me an idea for a one-liner that might work quite nicely:
Code:
Me.txtRecipients.Text = Join(Form1.ListEmail.List, vbNewLine)
This obviously won't work if you need to reverse the order, though.
EDIT: Sadly, that seems to throw an error, which is irritating. You'd think the List() and ItemData() arrays would be accessible as arrays, but I guess not. Maybe they're collections. (Though they don't have any of the telltale collection properties like Count.)
-
Re: Listbox to textbox
They are properties. If you create a class with similar properties, they will function the same way. Off-topic, see PM.