• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 168
  • Last Modified:

RomoveItem

I am trying to remove an item form a list box by selecting the item and clicking a button with the following code.  If I click on any item in the list other then the last one I get a error 381 (invalid property array index). Please help.

Private Sub cmdDelete_Click()
For intcounter = 0 To lstMain.ListCount - 1
If lstMain.Selected(intcounter) = True Then
lstMain.RemoveItem (intcounter)
End If
Next intcounter
End Sub
0
mad3654
Asked:
mad3654
  • 2
  • 2
  • 2
  • +1
1 Solution
 
imurphy76Commented:
Try this instead:

Private Sub cmdDelete_Click()
lstMain.RemoveItem lstMain.ListIndex
End Sub
0
 
imurphy76Commented:
Private Sub cmdDelete_Click()
lstMain.RemoveItem lstMain.ListIndex
End Sub

0
 
VbmasterCommented:
The correct way to remove the selected items from a multiselect-able listbox is using code like

   For intcounter = (lstMain.ListCount - 1) To 0
      If (lstMain.Selected(intcounter)) Then
         Call lstMain.RemoveItem(intcounter)
      End If
   Next

If you want to know why you got that problem with your old code.. it's because let's say you have a list with 3 items. You select the first item and then run the code. You first checks the first item, you see it is selected and removes it. Now you have a list of 2 items, and you check the 2nd item in the new list. Then you try to check the 3rd item (because you think that the list is 3 items) but there aint no such item and therefore you get that OutOfRange error.

Hope this helps.
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
paulstampCommented:
A simple remedy for your code (assuming single select in your listbox) is to add Exit For into your loop :

Private Sub cmdDelete_Click()
For intcounter = 0 To lstMain.ListCount - 1
If lstMain.Selected(intcounter) = True Then
    lstMain.RemoveItem (intcounter)
    Exit For
End If
Next intcounter
End Sub

0
 
paulstampCommented:
VBMaster.. don't you need a STEP -1 in your loop ??
0
 
VbmasterCommented:
Oops! Ye, to mad[blaha]: you need to add " Step -1" at the end of the For statement if you use the code from me.
0
 
mad3654Author Commented:
Thanks for the explaination also.
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 2
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now