# Listbox removeitem

I have a code here...hwen i tested it,
it works fine if i remove the item from the bottom then up one by one.
but if i try to pick it randomly to remove item then msgbox "Invalid Property index " is shown.
here is my code :

Private Sub Command2_Click()

For i = 0 To (List2.ListCount - 1)

If List2.Selected(i) = True Then
List2.RemoveItem (i)

End If
Next

End Sub

hope someone can help me...thks 1st
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
You will need to change it to..

For i = (List2.ListCount - 1) To 0 Step -1
If List2.Selected(i) = True Then
List2.RemoveItem (i)
End If
Next

With your old code you will try to access a item that is no more. Let's say you have a list with 5 items (max index 4), and you want to remove the first and last object. You remove the first item (index = 0) successfully, but what do you have left? You have 4 items with a maximum index of 3. Then when you try to get to List2.Selected(4) you will get that error you got.. You understand?
0
Commented:
Or simply jump out:
For i = 0 To (List2.ListCount - 1)
If List2.Selected(i) = True Then
List2.RemoveItem (i)
Exit For
End If
Next

Another thing to remember: a for-next loop is static, i.e. the "condition" is calculated once at the beginning of the loop and not calculated again. If you're going to be removing elements from a collection you're looking at a dynamic situation, in which case a do while loop is more appropriate:

intCounter = 0
Do While intCounter <= List2.ListCount - 1
If List2.Selected(intCounter) Then
List2.RemoveItem(intCounter)
Else
intCounter = intCounter + 1
End If
Loop
0
Commented:
caraf_g, i don't think he wants to bail out of the loop after only one deletion.
0
Commented:
In that case the do while solution will still work. Of course there's nothing wrong with VBMaster's solution ;-)
0
Commented:
If you just want to remove a selected item from a list when you click on that item then you should use.

Private Sub listName_Click()

listName.RemoveItem listName.ListIndex

End Sub

If you want to remove all the values from the list when you click on a list you could use.

Private Sub listName_Click()

Dim i As Integer
i = 0
While i < listName.ListCount
listName.RemoveItem (0)
Wend
End sub
0
Author Commented:
Sorry damienm...ur answer is not the solution to my q...
carf_g have given me the best answer.
thks for u all for the kind comment...

I should give the marks to caraf_g....thks again
0
Commented:
Thanks mictan
0

Experts Exchange Solution brought to you by