Home » excel » excel – Limit matches to three instead of unlimited

excel – Limit matches to three instead of unlimited

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m using a script to match one column (item #’s) based on another (image file names, which have the item # somewhere in it). I put the matched results in a middle column, each match separated by a ; delimiter.

Sub Adrift()
    Dim NA As Long, NC As Long, v As String, I As Long, J As Long
    Dim v2 As String
    NA = Cells(Rows.Count, "A").End(xlUp).Row
    NC = Cells(Rows.Count, "C").End(xlUp).Row
    For I = 2 To NA
        v = Cells(I, "A").Value
        v2 = ""
        For J = 2 To NC
            If InStr(Cells(J, "C").Value, v) > 0 Then
                v2 = v2 & "," & Cells(J, "C").Value
            End If
        Next J
        Cells(I, "A").Offset(0, 1).Value = Mid(v2,2)
    Next I
End Sub

I have up to 30 images per item # and want to limit this script to 3 or 4 matches.

Edit:

Say we have a worksheet like:

enter image description here

The above script scans column A (AMH4613A, AMH5706B, etc.) and then scans column C (note the image made it seem like column C is column B) against the values of column A. If there is a match (or a value from column A occurred in some part of the value in column C) the file name or value from column C is placed adjacent to the matching item # in column B.

Note Column C is very long, it’s a list of all the images in a directory. Column A (the item #’s) is about 1000 rows long while column C is about 5000. So there is about 5 images for every item on average, but not always.

The output would be like:

enter image description here

How to&Answers:

I’d probably do something like this with finds – should make it faster too.

Sub Adrift()
Dim NA As Long, NC As Long, I As Long
Dim Finder As Range, FAdd As String, Count As Integer
NA = Cells(Rows.Count, "A").End(xlUp).Row
NC = Cells(Rows.Count, "C").End(xlUp).Row
For I = 2 To NA
    Count = 0: Cells(I, "B").Value = ""
    Set Finder = Range("C1:C" & NC).Find(Cells(I, "A").Value, LookAt:=xlPart)
    If Not Finder Is Nothing Then
        FAdd = Finder.Address
        Do
            Cells(I, "B").Value = Cells(I, "B").Value & "," & Finder.Value
            Count = Count + 1
            Set Finder = Range("C1:C" & NC).FindNext(Finder)
        Loop While Finder.Address <> FAdd And Count < 3
        Cells(I, "B").Value = Mid(Cells(I, "B").Value, 2)
    End If
Next I
End Sub

You could lose the count variable and just count the commas in the string – and you could store it as a string instead of dropping it in the cell repeatedly – might make it faster too if speed was an issue.

And of course variant arrays are generally faster than find, though IMO it’s a decent use case for find.