简体   繁体   中英

Multiple Range.Find() in VBA

I have met this interesting problem today. I have a loop inside another loop and both use Find for different purposes. What happens is that using Find in the inside loop screws up the Find on the outer loop. I'm guessing keeps memory of only one search instance. Is there some way to work around this or is this a design matter ?

Here's some shortened version of my code.

Sub Main()
    'Some boring stuff

    Set lst_rapports = Worksheets("mappingTRANSIT").range("lst_rapports")
    Set first_result = lst_rapports.Find(rap_choisi)
    Set active_result = first_result

    Sheets("req01").Unprotect "shoobidoowap"
    If Not first_result Is Nothing Then
        ' ...            
        Do
            Sheets("req01").Select            
            ' ...
            For i = 0 To 4
                Set rubrique_cell = range("E:E").Find(rub(i))
                If Not rubrique_cell Is Nothing Then
                    ' ...
                End If
            Next i                
            ' Yet more boring stuff...

            Set active_result = lst_rapports.FindNext(active_result)
        Loop Until active_result.Address = first_result.Address
    Else
        MsgBox "Impossible de trouver """ & rap_choisi & """ !"
    End If
    Sheets("req01").Protect "shoobidoowap"
End Sub

Notice the second use of .Find in the for loop.

Is there some way I can preserve the first search in some kind of temporary variable and restore it back after that ?

Many thanks.

When you run FindNext (MSDN for FindNext) , it automatically uses the same what as the last call on Find , even if used for a different range.

To correct for this, instead of using

Set active_result = lst_rapports.FindNext(active_result)

use

Set active_result = lst_rapports.Find(rap_choisi,active_result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM