VBA (Excel): Find Based on Multiple Search Criteria Without Looping

后端 未结 2 508
耶瑟儿~
耶瑟儿~ 2020-12-09 06:39

I have a large data sheet that I want to search in VBA based on 3 sets of criteria. Each row entry can be assumed to be unique. The format of the sheet/data

相关标签:
2条回答
  • 2020-12-09 06:56

    You could use an Advanced Filter. Put the column headers in a separate part of the sheet (or a different sheet altogether). Under those column headers, put the criteria you're looking for in each column. Then name that range (including the headers) something like "Criteria". Then the macro becomes:

    Sub Macro1()
    
        Sheets("Sheet1").Range("A1").CurrentRegion.AdvancedFilter xlFilterInPlace, Range("Criteria")
    
    End Sub
    

    As a follow up to my comment below, to have the VBA create the criteria range behind the scenes:

    Sub Macro1()
    
        'Code up here that defines the criteria
    
        Application.ScreenUpdating = False
        Application.DisplayAlerts = False
    
        With Sheets.Add
            'Create the advanced filter criteria range
            .Range("A1") = "HeaderA"
            .Range("B1") = "HeaderB"
            .Range("C1") = "HeaderC"
            .Range("A2") = criteria1Name
            .Range("B2") = criteria2Name
            .Range("C2") = criteria3Name
    
            'Alternately, to save space:
            '.Range("A1:C1").Value = Array("HeaderA", "HeaderB", "HeaderC")
            '.Range("A2:C2").Value = Array(criteria1Name, criteria2Name, criteria3Name)
    
            'Then perform the advanced filter
            Sheets("Sheet1").Range("A1").CurrentRegion.AdvancedFilter xlFilterInPlace, .Range("A1:C2")
    
            'Remove behind the scenes sheet now that the filter is completed
            .Delete
        End With
    
        Application.ScreenUpdating = True
        Application.DisplayAlerts = True
    
    End Sub
    
    0 讨论(0)
  • 2020-12-09 07:16

    You can use EVALUATE for multiple criteria like so to return the row numbers of mathcing values. This uses the same approach as Is it possible to fill an array with row numbers which match a certain criteria without looping?

    • It searches 50000 rows to match
      • the first four letters in column A matches fred
      • the date in B to be greater than 1/1/2001
      • apple in column 5
    • Any rows matching these criteria are retuned as row numbers in x

    (rows 1 and 5 in picture below)

    code

    Sub GetEm2()
    x = Filter(Application.Transpose(Application.Evaluate("=IF((LEFT(A1:A10000,4)=""fred"")*(B1:B10000>date(2001,1,1))*(C1:C10000=""apple""),ROW(A1:A10000),""x"")")), "x", False)
    End Sub
    

    Application.Transpose is limited to 65536 cells, so a longer range needs to be "chunked" into pieces.

    enter image description here

    0 讨论(0)
提交回复
热议问题