Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting the second result of a "Find" with VBA

Tags:

find

excel

vba

I am trying to make it so that I can find the second result for "lights", in case of having various occurrences for this term. The code below finds the first occurrence in the range under consideration.

    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
like image 269
PocketLoan Avatar asked Jan 13 '23 13:01

PocketLoan


1 Answers

FindNext delivers what you want. Using it is easy: perform the first search as you are doing it right now (although by assigning the result to a Range) and take the resulting range as starting point for FindNext. Here you have a sample code adapted to your specific requirements (secondAddress is the Address of the second occurrence of "Light", if any):

   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
like image 104
varocarbas Avatar answered Jan 18 '23 15:01

varocarbas