2015-09-14 45 views
1

想要编写一个宏来搜索单元格范围内(或单元格后)的特定单词,在我们的例子中,我们说“hello”。假设我的电子表格如下:单元格范围内的宏搜索

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

试算表变化的内容每天,这样我可以有不同数量的“你好的日常生活。我想将最后一个'你好'旁边的数字(2)复制到另一个单元格。如果hello的字数不存在,它会将0放入该单元格中(请注意,即使字数为0,在此电子表格中可能仍有'hello')。最后一个Hello的位置将始终在单元格A17之后。

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

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

我也尝试使用内用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 

但它仍然会定位在电子表格中搜索到的第一个“你好”。

+0

忘了一段时间吧?试试'.Cells.Find(What:=“Hello”' – findwindow

+0

@findwindow It works !!!你能解释一下为什么吗?我真的是Vba的新手。非常感谢你。 – Summer

+0

你想限定' cells.find()'在你设置的范围内,所以你正确地做了一个'with'语句,但是这个语句的语法需要一个'''时间段才能知道是什么被限定的。 ://msdn.microsoft.com/en-us/library/wc500chb.aspx) – findwindow

回答

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