4

我正在努力做到这一点,以便我可以找到“灯”的第二个结果,以防该术语出现各种情况。下面的代码在考虑的范围内找到第一个匹配项。

    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
4

2 回答 2

5

FindNext提供你想要的。使用它很容易:像现在一样执行第一次搜索(尽管通过将结果分配给 a Range)并将结果范围作为FindNext. 在这里,您有一个适合您的特定要求的示例代码(如果有的话,secondAddressAddress第二次出现的“Light”):

   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
于 2013-08-23T13:23:58.347 回答
4

我找到了一种更简单的方法,因为听起来我遇到了类似的问题。

如果您简化了搜索功能:

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)开始搜索。

于 2015-04-24T01:00:33.283 回答