If each list conatains say 1000 items, with a nested loop you could be making 1000 x 1000 = 1 million comparisons.
Have you considered using an Exit For/Exit Do once a single match is found?
Are both lists already sorted (it looks like they may be)? If so, instead of comparing all values in one list with all values in the other, you could walk down both lists at the same time:
First compare both first items in the lists and see which one is smaller, then iterate down the list which had the smaller value until you get a match or the value is bigger, then stop running down that list and continue running down the other list until again, a match or bigger value is encountered etc. That way only 2000 comparisons get made.
Eg. using your example:
list A: "5, 45, 100, 113, 160"
list B: "2, 4, 45, 160, 189"
compare 5 and 2. 2 is smaller so run down list B:
compare 5 and 4
compare 5 and 45
stop at the 45 and start running down list A:
compare 45 and 45 (match, so add to the count)
compare 45 and 100
stop at 100 to flip over:
compare 100 and 160
stop at 160 to flip over:
compare 160 and 113
compare 160 and 160 (match, so add to the count)
compare 160 and 189
stop at 189 to flip over (or since you've come to the end of one of the lists there's no need to continue).
Using your example we need only make 8 comparisons instead of 25.
Perhaps post the code you already have?
Perhaps attach a workbook?
edit post posting:
something along these lines (neither debugged nor streamlined):Code:Sub blah() s1 = "5, 45, 100, 113, 160" s2 = "2, 4, 45, 160, 189" x = Split(s1, ",") y = Split(s2, ",") ix = 0: iy = 0 Do Until ix > UBound(x) Or iy > UBound(y) 'put ubounds into variables so that they don't need to be calculated in each iteration. 'Debug.Print x(ix), y(iy), IIf(CLng(x(ix)) = CLng(y(iy)), "Match!", "") If CLng(x(ix)) = CLng(y(iy)) Then Count = Count + 1 'I've assumed whole numbers; requires a tweak for singles or doubles. If CLng(x(ix)) >= CLng(y(iy)) Then iy = iy + 1 Else ix = ix + 1 Loop MsgBox Count & " item(s) in common" End Sub




Reply With Quote
Bookmarks