Re: Compare listbox items
Quote:
If list2 matches list1 then drop that item, however if it does not match then add the item to a list3 box.
Hope this helps...
Code:
Dim BoolAdd As Boolean, i As Long, j As Long
Private Sub Command1_Click()
'~~> Set initial Flag
BoolAdd = True
'~~> If list2 is empty then abort operation
If List2.ListCount = 0 Then
MsgBox "Nothing to compare"
Exit Sub
'~~> if list1 is empty then copy entire list2 to list3
ElseIf List1.ListCount = 0 Then
For i = 0 To List2.ListCount
List3.AddItem List2.List(i)
Next i
Else
For i = List2.ListCount - 1 To 0 Step -1
For j = 0 To List1.ListCount
If List2.List(i) = List1.List(j) Then
'~~> If match found then abort
BoolAdd = False
Exit For
End If
DoEvents
Next j
'~~> If not found then add to list3
If BoolAdd = True Then List3.AddItem List2.List(i)
DoEvents
Next i
End If
End Sub
Private Sub Form_Load()
'~~> Sample Data
'~~> Adding item to list1
List1.AddItem "Test"
List1.AddItem "Test2"
List1.AddItem "Test3"
'~~> Adding item to list2
List2.AddItem "Test2"
List2.AddItem "Test4"
List2.AddItem "Test5"
List2.AddItem "Test6"
End Sub
Re: Compare listbox items
Depending on how many items your listbox has, you may want to adapt koolsid's example using APIs vs looping thru both listboxes. Faux code looks a little like this & API search is tons faster:
Code:
For I = Listbox2.ListCount -1 to Step -1 ' work from bottom up
If SendMessage(ListBox1.hWnd, LB_FINDSTRINGEXACT, -1, ByVal ListBox2.List(I)) = -1 Then
' not found
... ListBox3.Add Item ListBox2.List(I), 0
Else ' found, remove it from #2
... ListBox2.RemoveItem I
End If
Next
Re: Compare listbox items