Excel vba范围.find函数阻止返回到第一个单元格
我有价值单元格L7,L12,L13,L14与下面的代码我可以find值并收集到范围。 但是在.find循环函数中,再次search到达第一个结果并退出.find函数。 问题是我接收范围L12,L13,L14,L7通常L7必须在开始。
我该如何解决呢? 我可以阻止.find返回第一个单元格,或者我可以sorting我用.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,而不是来自searchitem的L7
用这个
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
像这样尝试
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