Removing Items from Listbox

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I have a listbox on a form and I want the user to be able to select the items
to be removed from the list. But when I use the RemoveItem method on the
first selected row, all the other items in the list become UNselected and
therefore don't get removed. Can anyone help?
Thanks in advance,
 
By the way, I tried two different approaches with the same result.

#1
Dim lb As ListBox
Dim varItem As Variant
For Each varItem In lb.ItemsSelected
lb.RemoveItem Index:=varItem
Next varItem

#2
dim i as Integer
dim intIndex as Integer
dim lb as ListBox
For i = lngItemCount - 1 To 0 Step -1
If lb.Selected(i) = True Then
intIndex = i
lb.RemoveItem Index:=intIndex
End If
Next i
 
Untested, but should work:

Dim lb As ListBox
Dim varItem As Variant
Dim lngSelected() As Long
Dim lngLoop As Long

If lb.ItemsSelected.Count > 0 Then
ReDim lngSelected(lb.ItemsSelected.Count - 1)
lngLoop = 0
For Each varItem In lb.ItemsSelected
lngSelected(lngLoop) = varItem
lngLoop = lngLoop + 1
Next varItem
For lngLoop = UBound(lngSelected) To 0 Step -1
lb.RemoveItem Index:=lngLoop
Next lngLoop
End If
 
Doug:

Thanks for the response. There was just one thing I had to change in your
code for this to work. The line:

lb.RemoveItem Index:=lngLoop

didn't remove the correct row. It had be

lb.RemoveItem Index:=lngSelected(lngLoop)

because the index value was stored in the array lngSelected and the variable
lngLoop was the index to THAT array. But let me ask you one more thing,
please. How could I access one of the two fields in the row for the selected
items. I need to do something else with a piece of the data in addition to
removing it from the list. Specifically the field in Column(0).
Thanks again,
 
Not sure I understand your question.

If you're asking how to refer to the first column of an arbitray row in the
list box, it's

Me!NameOfListbox.Column(0, Rownumber)
 
Back
Top