【问题标题】:Excel vba range .find function prevent return back to first cellExcel vba range .find 函数防止返回到第一个单元格
【发布时间】:2017-04-08 15:07:37
【问题描述】:

我在单元格 L7、L12、L13、L14 上有值 使用下面的代码,我可以找到值并将其收集到范围。但是在 .find 循环函数搜索期间再次到达第一个结果并退出 .find 函数。 问题是我收到范围 L12、L13、L14、L7 通常 L7 必须在开头。

我该如何解决? 我可以阻止 .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 而不是来自 searchitem 的 L7

【问题讨论】:

    标签: vba excel


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      这样试试

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-12
        • 1970-01-01
        • 2017-12-12
        • 2013-01-24
        相关资源
        最近更新 更多