Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Loop over rows never ends

I have a list of around 20k rows and several columns. One of these columns contains comments. The code below iterates through the rows of the list, copies all the rows that have the comment "Date of Payment", and pastes them into another sheet.

But the loop never ends.

What is the problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is my code:

Sheets("MASTER").Select

rowslength = Range("O" & Rows.Count).End(xlUp).Row
'MsgBox rowslength

Set keyword1 = Cells.Find(what:="Date of Payment")
For i = 1 To rowslength
    keyword1.Select
    Selection.EntireRow.Select
    Selection.Copy
    With Sheets("Date of Payment").Range("a" & Rows.Count).End(xlUp).Offset(1)
    .PasteSpecial
    End With
    Sheets("MASTER").Select
    Set keyword1 = Cells.FindNext(keyword1)
    Application.CutCopyMode = False

Next i

>Solution :

As Warcupine said in the comments, you are looping from the first row to the last row in your populated range. Lets say this is 20,000 rows. But perhaps you only have 500 comments that match your criteria. Even though you copied all the data you need, the for loop will continue to process another 19,500 iterations. All you need to do is store the first occurrence before you enter the for-loop and then on each interation, check if the next found cell matches the first found cell. Like this:

Sub test()
    Sheets("MASTER").Select
    
    rowslength = Range("O" & Rows.Count).End(xlUp).Row
    'MsgBox rowslength
    
    Set keyword1 = Cells.Find(what:="Date of Payment")
    Set firstFoundCell = keyword1 'store the first found cell
    
    For i = 1 To rowslength
        keyword1.Select
        Selection.EntireRow.Select
        Selection.Copy
        With Sheets("Date of Payment").Range("a" & Rows.Count).End(xlUp).Offset(1)
            .PasteSpecial
        End With
        Sheets("MASTER").Select
        Set keyword1 = Cells.FindNext(keyword1)
        Application.CutCopyMode = False
        
        If keyword1.Address = firstFoundCell.Address Then Exit For 'stop when back at the first cell
    
    Next i
End Sub
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading