Home » excel » excel – .FindNext() with xlPrevious

excel – .FindNext() with xlPrevious

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m attempting to find all values “O” from bottom to top. I can’t use the “normal” find because I’m going to offset some values down and .Find() will find them again.

The problem is that when i use .FindNext after a .Find() with SearchDirection:=xlPrevious it goes back to the top instead of following the direction.

For test purposes I’m using this code:

Dim f As Range

Set ws = ThisWorkbook.ActiveSheet

ws.Cells(7, 5).Value = "O"
ws.Cells(6, 5).Value = "O"
ws.Cells(5, 5).Value = "O"
ws.Cells(5, 6).Value = "O"
ws.Cells(5, 7).Value = "O"

Set f = ws.Range("A1:AX50").Find(what:="O", SearchDirection:=xlPrevious)
Debug.Print f.Address
Set f = ws.Range("A1:AX50").FindNext(f)
Debug.Print f.Address

It prints $E$7 and $E$5. I was expecting $E$7 and $E$6.

I’m not sure this is the best method to find all values from bottom to top. Any help would be aprreciated.

How to&Answers:

The Range.FindNext method is clearly not inheriting the SearchDirection:=xlPrevious argument. You need the base Range.Find method with the After:=f argument instead.

Dim f As Range, addr As String, ws As Worksheet

Set ws = ThisWorkbook.ActiveSheet

ws.Cells(7, 5).Value = "O"
ws.Cells(6, 5).Value = "O"
ws.Cells(5, 5).Value = "O"
ws.Cells(5, 5).Value = "O"
ws.Cells(5, 6).Value = "O"
ws.Cells(5, 7).Value = "O"

With ws.UsedRange.Cells  'Range("A1:AX50")
    Set f = .Find(What:="O", after:=.Cells(1), SearchDirection:=xlPrevious, SearchOrder:=xlByRows)
    If Not f Is Nothing Then
        addr = f.Address(0, 0)
        Do
            Debug.Print f.Address
            Set f = .Find(What:="O", after:=f, SearchDirection:=xlPrevious, SearchOrder:=xlByRows)
        Loop Until addr = f.Address(0, 0)
    End If
End With