在一系列单元格中进行宏搜索

时间:2015-09-14 19:23:47

标签: excel vba excel-vba

想要编写一个宏来搜索一系列单元格中的特定单词(或单元格之后),在我们的例子中说“你好”。假设我的电子表格如下所示:

Hello用户
南希你好 你好算2

电子表格的内容每天都在变化,因此我每天可能会有不同数量的'Hello'。我想将最后一个'Hello'旁边的数字(2)复制到另一个单元格。如果hello的字数没有退出,它将在该单元格中输入0(注意,即使字数为0,在此电子表格中仍可能存在'hello')。最后一个Hello的位置将始终位于单元格A17之后。

我正在考虑将参数After设置为单元格A17,并将SearchOrder更改为xlByColumns,但是当搜索到达搜索范围的末尾时,它会回绕到范围的开头。

当这种环绕发生时,我应该如何停止搜索?

我还尝试使用With中的Find方法在范围A17到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

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

1 个答案:

答案 0 :(得分:0)

试试这个:

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")

结果:

Results

相关问题