Fastest / most elegant method for looping through a range to find values in excel VBA

后端 未结 1 1302
闹比i
闹比i 2021-01-29 00:15

Good day,

In my project, I encounter a number of situations in which I need my code to find a certain string multiple times in a given range, and do a number of actions

1条回答
  •  梦毁少年i
    2021-01-29 01:07

    If you want to continue an search, you can use FindNext rather than restart a new search.

    The only thing you need to be aware of is that FindNext will continue a search at the top once it is done. To be able to tell that the search starts again, you save the address of the first match and if FindNext returns you the address of your first match you know that you are done.

    One remark to your variable naming: Find/FindNext return Ranges, and you should gibe your variable a name that reflects that. FindStr impplies that it holds a string, which is not true. The default property of a Range is the value of it, so it may look as if it is a string - but it isn't.

    Have a look at this piece of code:

    Const searchStr = "MANUALLY"
    With .Sheets(c).Range("C2:C" & LRow)
        Dim findRange As Range, firstHit As Range
        Set findRange = .Find(searchStr, lookat:=xlWhole)
        If Not findRange Is Nothing Then
            Set firstHit = findRange     ' Remember first hit.
            Do
                ' ... (Do your stuff here)
                Set findRange = .FindNext(findRange)
            Loop While Not findRange Is Nothing And findRange.Address <> firstHit.Address
        Else
            ' in case you didn't find anything
        End If
    End With
    

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