F to copy rows with specific string missing a lot of rows

Hi, I hope you are well,

I am encountering a problem with a function/code that I built in order to:

Go through the rows of a sheet one after the other and :

-Copy the rows in which the first cell contains a string,

-Paste the rows in a second sheet

-Delete said rows on the parent file

The thing is, this code is partly working, some of the rows which contain the string are indeed copied and pasted but some arent ! And I am not understanding why.

The rows that are sucessfully copied also are not the same ones when I rearrange their place in the sheet

See below my code

My code:

Sub ctrlcctrlv()

Index1 = 1 'index for selecting parent sheet where to find rows
Index2 = 2 'index for sheet where to paste the rows

IndexL2 = 1 'index for pasting rows one after the other on sheet 2

anomalie = "example" 'the string I'm looking for

For Each rw In Worksheets(Index1).Rows
libellé = rw.Cells(1, 1) 'the string in first cell of my row for which I want to check if it contains the string I'm looking for
If InStr(1, libellé, anomalie) <> 0 Then
rw.Copy Worksheets(Index2).Rows(IndexL2)
rw.Delete
IndexL2 = IndexL2 + 1
End If
Next

End Sub


edit moderation : code put between code tags, using "</>" button on the menu bar. Please make sure to use it for future messages
.

Thank you very much for anyone who will take the time to answer.

I think i might change methods all over ... :[ maybe look for my string in the whole column directly and store the indexes that come up :(

Sincerely,

Hello Jeanne,

When you want to delete rows in the same time you're looking after items, you have to write your FOR-NEXT code from bottom to the top of the rows!!
Try this!

Have a happy new year!

Aha merci !! Mais bien sûr comment ai-je pu ne pas y penser plus tôt !!

Bonne nouvelle année à vous Curulis !

Search for threads similar to "copy rows specific string missing lot"