简体   繁体   中英

Macro search in a range of cells

Want to write a Macro that would search for a particular word in a range of cells (or after a cell), let's say "hello" in our case. Suppose my spreadsheet looks like this:

Hello user
Hello Nancy
Hello count 2

The content of the spread sheet change daily, so that I may have different number of 'Hello's everyday. I want to copy the number (2) beside the last 'Hello' to another cell. If the word count of hello doesn't exits, it will put 0 in that cell(Note that even if the word count is 0, there might still be 'hello' in this spread sheet). The location of the last Hello will always be after Cell A17.

I was thinking about setting the parameter After to cell A17, and change SearchOrder to xlByColumns, but When the search reaches the end of the search range, it wraps around to the beginning of the range.

How should I stop the search when this wraparound occurs?

I also try to use the Find method within With to search within range A17 to B22:

With Sheets("Data").Range("A17:B22")
    Set hello = Cells.Find(What:="hello", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
End With
If Not hello Is Nothing Then
    With Sheets("Data").Range("A17:B22")
        Cells.Find(What:="Hello", After:=ActiveCell, LookIn:=xlFormulas, _
            LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False).Activate
        ActiveCell.Offset(0, 1).Range("A1").Select
        Application.CutCopyMode = False
        Selection.Copy
        Range("B17").Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    End With
Else
    Range("B17").Select
    ActiveCell.FormulaR1C1 = "0"
End If

But it will still locate the search to the first 'Hello' in the spreadsheet.

Try This:

Function GetLastNumber(TheRange As Range, TheWord As String) As Variant
Dim Finder
'You can add LookAt:=xlWhole if you want entire word only
Set Finder = TheRange.Find(TheWord, SearchDirection:=xlPrevious)
If Finder Is Nothing Then
    GetLastNumber = CVErr(xlErrNA)
Else
    'Return the value of the cell one column to the right of our search word
    GetLastNumber = Finder.Offset(0, 1).Value
End If
End Function

You can use it like this:

Sub Test()
Range("D1") = GetLastNumber(Range("A1:A11"), "Hello")
End Sub

You can also use it as a formula:

=GetLastNumber(A1:A11,"Hello")

Results:

结果

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM