The crux of your problem is that when you remove multiple items from a listbox, you must do so in reverse - otherwise the listindex gets messed up. Here's an example with a listbox called "lstFood":
Code:
Dim intListX As Integer
For intListX = (lstFood.ListCount – 1) To 0 Step -1
If lstFood.Selected(intListX) Then
lstFood.RemoveItem intListX
End If
Next
To move items from one listbox to another, you can use the following code ("lstAvail" is the list of all available items, "lstSelected" is the is list of only the ones you want from the first list):
Code:
Dim intListX As Integer
For intListX = lstAvail.ListCount – 1 To 0 Step -1
If lstAvail.Selected(intListX) Then
lstSelected.AddItem lstAvail.List(intListX)
' If you are using the optional ItemData property array,
' add the following line to carry the "ItemData baggage" along ...
lstSelected.ItemData(lstSelected.NewIndex) = lstAvail.ItemData(intListX)
lstAvail.RemoveItem intListX
End If
Next
You could make a general purpose Sub to do this:
Code:
Public Sub MoveListBoxItems(lstListToAddTo As ListBox, _
lstListToRemoveFrom As ListBox)
Dim intListX As Integer
For intListX = lstListToRemoveFrom.ListCount – 1 To 0 Step -1
If lstListToRemoveFrom.Selected(intListX) Then
lstListToAddTo.AddItem lstListToRemoveFrom.List(intListX)
lstListToAddTo.ItemData(lstListToAddTo.NewIndex) _
= lstListToRemoveFrom.ItemData(intListX)
lstListToRemoveFrom.RemoveItem intListX
End If
Next
End Sub
Assuming you had two command buttons called "cmdAdd" and "cmdRemove", with the above Sub incorporated into your project, you could use the following code in the cmdAdd_Click and cmdRemove_Click events to call the MoveListBoxItems Sub:
Code:
Private Sub cmdAdd_Click()
MoveListBoxItems lstSelected, lstAvail
End Sub
Private Sub cmdRemove_Click()
MoveListBoxItems lstAvail, lstSelected
End Sub