Link to home
Start Free TrialLog in
Avatar of mictan
mictan

asked on

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
Avatar of Vbmaster
Vbmaster

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?
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
caraf_g, i don't think he wants to bail out of the loop after only one deletion.
In that case the do while solution will still work. Of course there's nothing wrong with VBMaster's solution ;-)
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
Avatar of mictan

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of caraf_g
caraf_g

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial