Home » excel » how to get more than one cell address out of `find` method in excel vba

how to get more than one cell address out of `find` method in excel vba

Posted by: admin May 14, 2020 Leave a comment

Questions:

This little macro returns the first cell address where the zip code matches. I need all of the cells where the zip code matches. Do I loop through somehow or does the find method offer more than one answer?

Sub practiceFind()

    Dim wsVendor As Worksheet:                Set wsVendor = Worksheets("vendorOutput.csv")
    Dim zipColumnVendor As Integer:         zipColumnVendor = 5
    Dim vendorRows As Integer:                   vendorRows = wsVendor.Cells(Rows.Count, 1).End(xlUp).Row ' less 1 for label row

    Dim searchRange As Range
    Set searchRange = Worksheets("vendorOutput.csv").Range(Cells(2, zipColumnVendor), Cells(vendorRows, zipColumnVendor))

    Dim x As Range

    Set x = searchRange.Find(what:="10514", LookIn:=xlValues, LookAt:=xlPart)
    MsgBox x.Address

End Sub
How to&Answers:

You can call FindNext on searchRange with x to get the next match.

Example:

Sub practiceFind()

    Dim wsVendor As Worksheet:                Set wsVendor = Worksheets("vendorOutput.csv")
    Dim zipColumnVendor As Integer:         zipColumnVendor = 5
    Dim vendorRows As Integer:                   vendorRows = wsVendor.Cells(Rows.Count, 1).End(xlUp).Row ' less 1 for label row

    Dim x As Range    

    With Worksheets("vendorOutput.csv").Range(Cells(2, zipColumnVendor), Cells(vendorRows, zipColumnVendor)) 
        Set x = .Find(what:="10514", LookIn:=xlValues, LookAt:=xlPart) 
        If Not x Is Nothing Then 
            firstAddress = x.Address
            Do 
                MsgBox x.Address
                Set x = .FindNext(x) 
            Loop While Not x Is Nothing And x.Address <> firstAddress
        End If 
    End With

End Sub

Answer:

Instead of a find, you could do a filter:

Set searchRange = Worksheets("vendorOutput.csv").Range(Cells(1, zipColumnVendor), Cells(vendorRows, zipColumnVendor))

With searchRange
    .AutoFilter 1, 10514
    On Error Resume Next
    Set x = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    .AutoFilter
End With

If Not x is Nothing Then MsgBox x.Address