Removing Items from Listbox

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,
 
G

Guest

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
 
D

Douglas J. Steele

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
 
G

Guest

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,
 
D

Douglas J. Steele

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)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top