I have a userform with two listboxes side by side. I want the left listbox to contain a large list of items, and the user can select those they want and send them to the listbox on the right. This does not remove the items from the listbox on the left. Items on the left are unique.
I don't want users to be able to send the same item twice to the list on the right, so I have the following sub to check for duplicates first:
Sub ToRight(ctrlLeft As control, ctrlRight As control)
Dim i As Integer, j As Integer
Dim there As Boolean
For i = 0 To ctrlLeft.ListCount - 1
If ctrlLeft.Selected(i) = True Then
there = False
For j = 0 To ctrlRight.ListCount - 1
If ctrlRight.List(j) = ctrlLeft.List(i) Then
there = True
End If
Next
If there = False Then ctrlRight.addItem ctrlLeft.List(i)
End If
Next
End Sub
For each selected item in the left listbox, it will check every item in the right listbox to see if there is a match, and only add it if there is no match. That is very slow once there are around 1000 entries in the list (it can happen) and the userform actually hides itself after running the code (5 seconds). I have to minimize and re-maximize the Excel application for the userform to show again (and it is modal).
How can I send items to the right listbox without such a painful loop? Or how can I make the loop less expensive so it doesn't crash the userform?