PDA

View Full Version : Solved: Removing a Item from Listbox.



abhay_547
06-02-2010, 08:06 AM
Hi All,

I have a Textbox and a Listbox on a excel userform and I have a two Command buttons one is "Add" and another one is "Remove". I have written the following code in my excel userform background. Basically what I am trying to do is when I type something in my text box and click on the "Add" button then it should add text entered by me in textbox to listbox as a new item and when I select the some of the items in my listbox and click on "Remove" button then it should remove all those selected items from my listbox. I have set my listbox property as below.
Linestyle = 1 and MultiSelect = 1.

Following is the code which I have :
Private Sub Add_Click()
ListBox1.AddItem TextBox1.Value
End Sub
Private Sub Remove_Click()
ListBox1.Selected Clear
End Sub


Above code works fine when I "Add" something using command button "Add" but when I try to "Remove" some of the items from the multiple items reflecting in listbox1 (which were added by me using textbox) it doesn't work. Please help.

Thanks a lot for your help in advance.

Bob Phillips
06-02-2010, 08:55 AM
Private Sub Remove_Click()
Dim i As Long
With Me.ListBox1
For i = .ListCount - 1 To 0 Step -1
If .Selected(i) Then
.RemoveItem .ListIndex
End If
Next i
End With

End Sub

abhay_547
06-03-2010, 08:29 AM
Hi,

Thanks a lot for your reply, But the code provided you doesn't work fine. It doesn't remove all selected items properly. Following are details.

1) I have added four Items from textbox to listbox and if I try to remove only 2 and 3 item from listbox then it removes all of them or leaves only item behind. It's behaving in a wierd manner I am not able to figure out because the code looks fine. Any suggestions.

Thanks a lot for your help in advance.:bow:

mdmackillop
06-03-2010, 08:59 AM
Can you post your workbook?

abhay_547
06-27-2010, 12:42 AM
Hi All,

Thanks a lot guys, It's working now.:hi: