VB Code:
Private Sub Command1_Click() List1.AddItem "item" List1.AddItem "item" List1.AddItem "item" End Sub
How could I make the ListBox automatically remove items with the same name?
Printable View
VB Code:
Private Sub Command1_Click() List1.AddItem "item" List1.AddItem "item" List1.AddItem "item" End Sub
How could I make the ListBox automatically remove items with the same name?
Just specify the index number instead unless that is if you are wanting to remove them all.
VB Code:
'Remove just the selected item: List1.RemoveItem List1.ListIndex 'Remove the second item: List1.RemoveItem 1
Did you mean if listbox having same items then remove it automatically
same items??
Also, it would be best to prevent the duplicates from being added in the first place. ;)
Yes Nida u got my point.
That's not exactly what I'm looking for. For example In List1 there are the following items:
adf
fdasf
fdas
df
dsafd
213dfas
fdasdfsa
dfsaf
dsafd
yr7
658i
gh
87udj
gh
asdf
uy
e5er
sdawf
dasf
aas
aas
htry
asfd
aas
I want a command that would remove all items that are duplicates. Except one (because one needs to stay).
Oh, well this will do it for you that way then.
VB Code:
Option Explicit Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Long, _ ByVal wMsg As Long, ByVal wParam As Long, ByRef lParam As Any) As Long Private Const LB_FINDSTRINGEXACT As Long = &H1A2 Private Const LB_FINDSTRING As Long = &H18F Private Sub Command1_Click() Dim i As Integer Dim lRet As Long For i = List1.ListCount - 1 To 0 Step -1 lRet = SendMessage(List1.hwnd, LB_FINDSTRINGEXACT, ByVal 0&, ByVal List1.List(i)) If lRet <> i Then List1.RemoveItem lRet End If Next End Sub Private Sub Form_Load() List1.AddItem "Test1" List1.AddItem "Test1" List1.AddItem "Test2" List1.AddItem "Test2" List1.AddItem "Test2" List1.AddItem "Test3" End Sub
Try this code, ofcourse this is meant for a combobox but I am sure someone can do this for listbox. I would have done it but don't have VB installed on the computer I am serfing the net from :(
VB Code:
Private Const CB_FINDSTRINGEXACT = &H158 Private Const CB_ERR = (-1) Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" _ (ByVal hwnd As Long, ByVal wMsg As Long, _ ByVal wParam As Long, lParam As Long) As Long Private Sub cmdRemoveDups() Dim x As Integer, y As Integer For x = cmbSortServiceDate.ListCount - 1 To 0 Step (-1) y = SendMessage(cmbSortServiceDate.hwnd, CB_FINDSTRINGEXACT, CB_ERR, ByVal cmbSortServiceDate.List(x)) If y <> x And y <> CB_ERR Then cmbSortServiceDate.RemoveItem x End If Next End Sub
Thanks you guys.