2012-10-09 160 views
2

我今天遇到了这个有趣的问题。我在另一个循环内部有一个循环,两者都使用Find用于不同的目的。会发生什么情况是在内部循环中使用Find将外部循环中的Find拧紧。我猜只保留一个搜索实例的内存。有没有办法解决这个问题,或者这是一个设计问题?VBA中的多个Range.Find()

这里是我的代码的一些缩写版本。

Sub Main() 
    'Some boring stuff 

    Set lst_rapports = Worksheets("mappingTRANSIT").range("lst_rapports") 
    Set first_result = lst_rapports.Find(rap_choisi) 
    Set active_result = first_result 

    Sheets("req01").Unprotect "shoobidoowap" 
    If Not first_result Is Nothing Then 
     ' ...    
     Do 
      Sheets("req01").Select    
      ' ... 
      For i = 0 To 4 
       Set rubrique_cell = range("E:E").Find(rub(i)) 
       If Not rubrique_cell Is Nothing Then 
        ' ... 
       End If 
      Next i     
      ' Yet more boring stuff... 

      Set active_result = lst_rapports.FindNext(active_result) 
     Loop Until active_result.Address = first_result.Address 
    Else 
     MsgBox "Impossible de trouver """ & rap_choisi & """ !" 
    End If 
    Sheets("req01").Protect "shoobidoowap" 
End Sub 

请注意,在第二使用的.Find for循环。

是否有某种方法可以保留某种临时变量中的第一个搜索并在此之后恢复它?

非常感谢。

回答

5

当您运行FindNext(MSDN for FindNext),它会自动使用相同的whatFind最后一次通话,即使用于不同的范围。

为解决这个问题,而不是使用

Set active_result = lst_rapports.FindNext(active_result)

使用

Set active_result = lst_rapports.Find(rap_choisi,active_result)

+0

我会尝试这个明天! – ApplePie