简体   繁体   中英

Delete pairs of rows based on value in column

A testing machine tests parts at two different speeds: 50 and 200 rpm. The machine outputs the data for each part at each speed such that

Row 1 = part 1 at 50 rpm
Row 2 = part 1 at 200 rpm
Row 3 = part 2 at 50 rpm
Row 4 = part 2 at 200 rpm

and so on for about 23,000 parts.

If a part number failed for a specific speed, the data would show "niO" in column H of that row, but it would only show it for that speed. I'm trying to write a macro that will check if a row contains the "niO" value, and then delete both that row, and the row for the other speed. Here's the code I have so far:

Sub DeleteFailures()

Dim r As Long

Dim lastrow As Long

lastrow = Cells(Rows.Count, "A").End(xlUp).Row

For r = 1 To lastrow

    If Cells(r, "H").Value = "n.i.O." Then

        If Cells(r, "E").Value = "50" Then

            Rows(r + 1).EntireRow.Delete

            Rows(r).EntireRow.Delete

        ElseIf Cells(r, "E").Value = "200" Then

            Rows(r - 1).EntireRow.Delete

            Rows(r).EntireRow.Delete

        End If

    Else

    End If

Next

End Sub

This doesn't seem to want to work for me. I think the problem might be that it skips a row every time one is deleted, but I'm not sure. Is there another approach that might work better?

It's exactly the reason you're thinking about. To make it work you should loop beginning the bottom:

For r = lastrow To 1 Step -1

The whole For loop block I believe should look like this (changed ElseIf part):

For r = lastrow To 1 Step -1
    If Cells(r, "H").Value = "n.i.O." Then
        If Cells(r, "E").Value = "50" Then
            Rows(r + 1).EntireRow.Delete
            Rows(r).EntireRow.Delete
        ElseIf Cells(r, "E").Value = "200" Then
            Rows(r).EntireRow.Delete
            Rows(r - 1).EntireRow.Delete
            r = r - 1
        End If
    Else
    End If
Next

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