在一系列单元格中进行macrossearch

想要编写一个macros来search单元格区域(或单元格区域)中的特定单词,在我们的例子中,我们说“你好”。 假设我的电子表格如下所示:

你好用户
南希你好
你好数2

电子表格的内容每天都在变化,所以我可能会有不同数量的“你好,每天”。 我想复制最后一个“你好”旁边的数字(2)到另一个单元格。 如果hello的字数不存在,它将把0放在那个单元格中(注意,即使字数是0,在这张电子表格中可能仍然是'hello')。 最后一个Hello的位置将始终在单元格A17之后。

我正在考虑将单元格A17之后的参数设置为“后”,然后将SearchOrder更改为xlByColumns,但是当search到达search范围的末尾时,它会绕回到范围的开头。

当这个环绕发生时,我应该如何停止search?

我也尝试使用With中的Find方法在范围A17到B22中search:

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 

但它仍然会将search定位到电子表格中的第一个“Hello”。

尝试这个:

 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 

你可以像这样使用它:

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

你也可以用它作为公式:

 =GetLastNumber(A1:A11,"Hello") 

结果:

结果