Francis
Francis

Reputation: 792

Excel VBA looping infinitely

I'm quite new to VBA

I'm getting an infinite loop with the code below, when I'm expecting the search to stop on reaching the last occurrence. (I have 2 cells in the current workspace that contain >>>). Can anyone tell me what is going wrong?

Set titles = Range("A1:A1")
Dim bEndLoop As Boolean
bEndLoop = False
' lookup part of content in search
mCurLookup = xlPart
With possibleTitles
    Do While Not bEndLoop
        Set titles = .Find(What:=">>>", After:=ActiveCell)
        If Not titles Is Nothing Then
               Application.Goto titles, True
                MsgBox (titles.Address)
                titles.Activate
            Else
                MsgBox "Nothing found"
                bEndLoop = True
            End If
    ' Set t2 = titles(1).CurrentRegion
    Loop
End With

Upvotes: 0

Views: 285

Answers (2)

Tom
Tom

Reputation: 9878

Below is an example of your code using a Find FindNext method. Using this method is far faster then using a For Loop equivalent

Dim titles As Range
Dim possibleTitles As Range
Dim firstAddress As String

Set possibleTitles = ActiveSheet.Range("A:A")

With possibleTitles
    Set titles = .Find(what:=">>>")
    If Not titles Is Nothing Then
        firstAddress = titles.Address

        Do
            MsgBox titles.Address
            Set titles = .FindNext(titles)
        Loop Until firstAddress = titles.Address
    End If
End With

Upvotes: 2

Francis
Francis

Reputation: 792

guess the answer should look like this (from https://learn.microsoft.com/en-us/office/vba/api/excel.range.findnext ) I don't like the 2-part Find then FindNext (can't I have just one loop?), but then if it's the official way of doing it I guess it's better to stick to that.

With Worksheets(1).Range("a1:a500")
     Set c = .Find(2, lookin:=xlValues)
     If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            c.Value = 5
            Set c = .FindNext(c)
            If c is Nothing Then Exit Do
        Loop While c.Address <> firstAddress
      End If
End With

Upvotes: 2

Related Questions