2015-09-14 43 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