3

I'm trying to search a worksheet for a row where the values in the first 3 columns match a set of 3 criteria. I'm using this linear search:

Function findRow(pName as string,fNo as string,mType as string) As Long

Dim rowCtr As Long

rowCtr = 2
While Not rowMatchesCriteria(rowCtr, pName,fNo,mType)
    rowCtr = rowCtr + 1
Wend
findRow=rowCtr

End Function



Function rowMatchesCriteria(row As Long, pName As String, fNo As String, mType As String) As Boolean

rowMatchesCriteria = dSheet.Cells(row,1)=pName _
                        And dSheet.Cells(row,2)=fNo _
                        And dSheet.Cells(row,3)=mType

End Function

We can assume that for any 3 criteria, there is only one match. However, this is very slow. dSheet has ~35,000 entries to search through, and I need to perform ~400,000 searches.

I looked at some of the solutions in this question, and while I'm sure that using AutoFilter or an advanced would be faster than a linear search, I don't understand how to get the index of the row that the filter returns. What I'm looking for would be:

Sub makeUpdate(c1 as string,c2 as string,c3 as string)

Dim result as long

result = findRow(c1,c2,c3)

dSheet.Cells(result,updateColumn) = someUpdateValue

End Sub

How do I actually return the result row that I'm looking for once I've applied AutoFilter?

Community
  • 1
  • 1
sigil
  • 9,370
  • 40
  • 119
  • 199
  • 1
    look at my answer here: http://stackoverflow.com/questions/21091948/searching-over-multiple-columns-in-excel-vba/21092259#21092259 – Dmitry Pavliv May 08 '14 at 19:35
  • 1
    @simoco, the `SpecialCells(xlCellTypeVisible)` is what I was thinking of. Thanks for the link. – sigil May 08 '14 at 20:31

4 Answers4

3

For performance you're hard-pressed to beat a Dictionary-based lookup table:

Sub FindMatches()

    Dim d As Object, rw As Range, k, t
    Dim arr, arrOut, nR, n

    t = Timer

    'create the row map (40k rows)
    Set d = GetRowLookup(Sheets("Sheet1").Range("A2:C40001"))

    Debug.Print Timer - t, "map"
    t = Timer

    'run lookups on the row map
    '(same values I used to create the map, but randomly-sorted)
    For Each rw In Sheets("sheet2").Range("A2:C480000").Rows
        k = GetKey(rw)
        If d.exists(k) Then rw.Cells(3).Offset(0, 1).Value = d(k)
    Next rw

    Debug.Print Timer - t, "slow version"
    t = Timer

    'run lookups again - faster version
    arr = Sheets("sheet2").Range("A2:C480000").Value
    nR = UBound(arr, 1)
    ReDim arrOut(1 To nR, 1 To 1)
    For n = 1 To nR
        k = arr(n, 1) & Chr(0) & arr(n, 2) & Chr(0) & arr(n, 3)
        If d.exists(k) Then arrOut(n, 1) = d(k)
    Next n
    Sheets("sheet2").Range("D2").Resize(nR, 1).Value = arrOut

    Debug.Print Timer - t, "fast version"

End Sub  


'create a dictionary lookup based on three column values
Function GetRowLookup(rng As Range)
    Dim d As Object, k, rw As Range
    Set d = CreateObject("scripting.dictionary")
    For Each rw In rng.Rows
        k = GetKey(rw)
        d.Add k, rw.Cells(1).Row 'not checking for duplicates!
    Next rw
    Set GetRowLookup = d
End Function

'create a key from a given row
Function GetKey(rw As Range)
    GetKey = rw.Cells(1).Value & Chr(0) & rw.Cells(2).Value & _
              Chr(0) & rw.Cells(3).Value
End Function
Tim Williams
  • 154,628
  • 8
  • 97
  • 125
1

If you want to do an exact lookup on 3 columns, you can use VLOOKUP using a slight trick: you create a key based on your 3 columns. E.g. if you want to perform your query on columns B, C, D, create a key column in A based on your three columns (e.g. =B1&C1&D1). Then:

=VLOOKUP(lookupvalue1&lookupvalue2&lookupvalue3,A:D,{2,3,4},FALSE)  

should do the magic.

pnuts
  • 58,317
  • 11
  • 87
  • 139
Bjoern Stiel
  • 3,918
  • 1
  • 21
  • 19
0

One simple solution could be using excel function MATCH as array formula. No for-each loops so I guess this could run very fast.

Formula will look e.g. like this MATCH("A"&"B"&"C",RANGE_1&RANGE_2&RANGE_3,0)

Option Explicit

Private Const FORMULA_TEMPLATE As String = _
    "=MATCH(""CRITERIA_1""&""CRITERIA_2""&""CRITERIA_3"",RANGE_1&RANGE_2&RANGE_3,MATCH_TYPE)"

Private Const EXACT_MATCH = 0

Sub test()
    Dim result
    result = findRow("A", "B", "C")
    Debug.Print "A,B,C was found on row : [" & result & "]"
End Sub

Function findRow(pName As String, fNo As String, mType As String) As Long

    On Error GoTo Err_Handler

    Dim originalReferenceStyle
    originalReferenceStyle = Application.ReferenceStyle
    Application.ReferenceStyle = xlR1C1

    Dim data As Range
    Set data = ActiveSheet.UsedRange

    Dim formula As String

    ' Add criteria
    formula = Replace(FORMULA_TEMPLATE, "CRITERIA_1", pName)
    formula = Replace(formula, "CRITERIA_2", fNo)
    formula = Replace(formula, "CRITERIA_3", mType)

    ' Add ranges where search
    formula = Replace(formula, "RANGE_1", data.Columns(1).Address(ReferenceStyle:=xlR1C1))
    formula = Replace(formula, "RANGE_2", data.Columns(2).Address(ReferenceStyle:=xlR1C1))
    formula = Replace(formula, "RANGE_3", data.Columns(3).Address(ReferenceStyle:=xlR1C1))

    ' Add match type
    formula = Replace(formula, "MATCH_TYPE", EXACT_MATCH)

    ' Get formula result
    findRow = Application.Evaluate(formula)

Err_Handler:
    ' Set reference style back
    Application.ReferenceStyle = originalReferenceStyle

End Function

Output: A,B,C was found on row : [4]

Data:

Daniel Dušek
  • 13,683
  • 5
  • 36
  • 51
0

In order to improve the best answer (multi criteria search), you would want to check for duplicates to avoid error.

'create a dictionary lookup based on three column values
Function GetRowLookup(rng As Range)
    Dim d As Object, k, rw As Range
    Set d = CreateObject("scripting.dictionary")
    For Each rw In rng.Rows
        k = GetKey(rw)
        if not d.exists(k) then
            d.Add k, rw.Cells(1).Row 'checking for duplicates!
        end if
    Next rw
    Set GetRowLookup = d
End Function