2017-04-08 136 views
1

我有單元格L7,L12,L13,L14 上的值與下面的代碼我可以找到值並收集到範圍。但在.find循環函數搜索期間,再次到達第一個結果並退出.find函數。 問題是我收到範圍L12,L13,L14,L7 通常L7必須在開始。Excel vba範圍.find函數防止返回到第一個單元格

我該如何解決? 我可以阻止.find返回第一個單元格嗎?或者我可以使用.find對我得到的範圍進行排序嗎?

Function FindAll1(rngLookIn As Range, LookFor) As Range 


Dim rv As Range, c As Range, FirstAddress As String 
With rngLookIn 
    Set c = .Find(LookFor, After:=Range("L2"), LookIn:=xlValues, lookat:=xlWhole) 
    If Not c Is Nothing Then 
     FirstAddress = c.Address 
     Set rv = c 
     Do 
      Set c = .FindNext(c) 
      If Not c Is Nothing Then Set rv = Application.Union(rv, c) 
     Loop While Not c Is Nothing And c.Address <> FirstAddress 
    End If 
End With 
Set FindAll1 = rv 
End Function 

這是我的代碼調用函數

Set searchitem = FindAll1(arama, aranan) 

    If Not searchitem Is Nothing Then 

     For Each g In searchitem.Cells 

我的代碼從這裏開始,但它配備L12的第一而不是L7從searchitem

回答

1

使用本

Function FindAll1(rngLookIn As Range, LookFor) As Range 
    Dim rv As Range, c As Range, FirstAddress As String 
    With rngLookIn 
     Set c = .Find(LookFor, After:=.Cells(.Count), LookIn:=xlValues, lookat:=xlWhole) '<--| force the passed range last cell as the one to start searching for -> this will make the first matching one as the first to be listed 
     If Not c Is Nothing Then 
      FirstAddress = c.Address 
      Set rv = c 
      Do 
       Set rv = Application.Union(rv, c) '<--| first, update union 
       Set c = .FindNext(c) '<--| then, seach next match 
      Loop While Not c Is Nothing And c.Address <> FirstAddress '<--| exit if reached the first match -> this will prevent adding first matching cell to union again 
     End If 
    End With 
    Set FindAll1 = rv 
End Function 
+0

它的工作原理感謝您的幫助! – Teo

+0

不客氣 – user3598756

0

嘗試它像這

Function FindAll1(rngLookIn As Range, LookFor) As Range 
Dim rv As Range, c As Range, FirstAddress As String 
With rngLookIn 
    Set c = .Find(LookFor, After:=Range("L2"), LookIn:=xlValues, lookat:=xlWhole) 
    FirstAddress = c.Address 
    If Not c Is Nothing Then 
     Do 
      If rv Is Nothing Then 
       Set rv = c 
      Else 
       Set rv = Union(rv, c) 
      End If 
      Set c = .FindNext(c) 

     Loop While Not c Is Nothing And c.Address <> FirstAddress 
    End If 
End With 
Set FindAll1 = rv 
End Function 
相關問題