2013-08-23 64 views
4

我試圖讓它能夠找到「燈光」的第二個結果,以防萬一出現此術語的各種情況。下面的代碼找到所考慮範圍內的第一個事件。使用VBA選擇「查找」的第二個結果

Dim ws As Worksheet 
    Dim rng1 As Range 
    Dim y As Range 

    Columns("B:B").Select 
Selection.Find(What:="1", After:=ActiveCell, LookIn:=xlValues, LookAt:= _ 
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _ 
    , SearchFormat:=False).Select 
    Set x = Range(Selection, Selection.End(xlDown)).Offset(0, 3) 
    Range(x.Address(0, 0)).Select 
    Selection.Find(What:="Lights", After:=ActiveCell, LookIn:=xlValues, LookAt:= _ 
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _ 
    , SearchFormat:=False).Activate 

     Selection.FindNext(After:=ActiveCell).Activate 
     Selection.FindNext(After:=ActiveCell).Select 
+1

你的代碼有點混亂。你能解釋一下你打算做什麼嗎?首先搜索「1」,然後搜索「Lights」(在發現「1」的範圍內)。用簡單的語言說出你想要做什麼。 – varocarbas

+0

該代碼在列b中找到「1」,然後將活動單元移動到列b中包含1的行的列e,然後選擇一個範圍,直到被佔用單元的末尾......它的最後部分開始與光找到是關鍵部分。我希望它能找到第n個(即第二個或第三個) –

+1

你的問題很清楚,我問過要確保上面的代碼正在做你想做的事情,請馬上寫下我的答案 – varocarbas

回答

5

FindNext提供你想要的。使用它很簡單:按照您現在的操作進行第一次搜索(儘管將結果分配給Range),並將結果範圍作爲起始點FindNext。這裏有一個示例代碼適用於您的具體要求(secondAddress是「光」的第二次出現的Address,如果有的話):

Dim foundRange As Range 
    Dim rangeToSearch As Range 
    Set rangeToSearch = Selection 
    Set foundRange = rangeToSearch.Find(What:="Lights", After:=ActiveCell, LookIn:=xlValues, LookAt:= _ 
    xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _ 
    , SearchFormat:=False) 'First Occurrence 

    Dim secondAddress As String 
    If (Not foundRange Is Nothing) Then 
     foundRange.Activate 
     Dim count As Integer: count = 0 
     Dim targetOccurrence As Integer: targetOccurrence = 2 
     Dim found As Boolean 

     Do While Not found 
      Set foundRange = rangeToSearch.FindNext(foundRange) 
      If Not foundRange Is Nothing Then 
       count = count + 1 
       If (count >= targetOccurrence - 1) Then 
        secondAddress = foundRange.Address 
        Exit Do 
       End If 
      Else 
       Exit Do 
      End If 
     Loop 
    End If 
+0

工程很好,應該找到範圍。下一個(目前foundrange下) –

+1

@RichardPullman實際上剛剛找到了Range,這是一個錯字,很抱歉。 – varocarbas

3

我發現了一個更簡單的方法,因爲它聽起來像我有一個類似問題。

如果您簡化您的搜索功能:

Cells.Find(What:="xxxx", After:=Cells(1, 1), LookIn:=xlValues, _ 
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False).Select 

然後添加另一條線之下:

Cells.Find(What:="xxxx", After:=ActiveCell, _ 
LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, _ 
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False).Select 

這樣做只是找到「XXXX」的第一次出現,那麼第二個代碼發現「 xxxx「,但是從第一個查找代碼(這是ActiveCell)的結果開始搜索。

相關問題