简体   繁体   中英

Loop trought my rows and delete row if 2 cells contains any value

IMAGE

Would like to make this as a for loop which itherate and compare A1 with B1 if they both contains a value detele otherwhise skip and jump to the next row and compare A2 with B2, A3 with B3 and so on till about 100.

You can see in my example IMAGE, like A4 contains a value but B4 doesn't so skip,A5 and B5 same, but A6 and B6 Both contains a value so I would like to delete the row, and carry on :)

Sub Empty_cell()

    Dim score1 As Integer, score2 As Integer, result As String, col As Integer, RangeStr1 As String, RangeStr2 As String

    col = 4
    Let RangeStr1 = "A" & col & ""
    Let RangeStr2 = "B" & col & ""

    score1 = Range(RangeStr1).Value
    score2 = Range(RangeStr2).Value

    If score1 >= 0 & score2 >= 0 Then

        Range(RangeStr1 & ":" & RangeStr2).Delete
        MsgBox "Deleted"
    Else
        MsgBox "Failed"
        col = col + 1 '

        MsgBox col
    End If
End Sub

you can do it with a one liner statement:

Range("A4", Cells(Rows.count, "A").End(xlUp)).SpecialCells(xlCellTypeConstants, xlNumbers).Offset(, 1).SpecialCells(xlCellTypeConstants, xlNumbers).EntireRow.Delete

where:

  • Range("A4", Cells(Rows.count, "A").End(xlUp))

    references all column A cells from row 4 down to last not empty one

  • .SpecialCells(xlCellTypeConstants, xlNumbers)

    selects all referenced range cells with a number

  • .Offset(, 1).

    shifts resulting range one column to the right (ie to corresponding cells of column B)

  • .SpecialCells(xlCellTypeConstants, xlNumbers)

    selects this latter referenced range cells with a number

  • .EntireRow.Delete

    finally deletes the row of the resulting cells

Nothing at all wrong with user3598756 solution at all. Just providing something which is a bit mroe robust and perhaps adaptable

Let me know your thoughts:

Option Explicit
Dim n As Long
Dim i As Long
Sub DeleteRows()

n = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row

For i = 4 To n
    Select Case Cells(i, 1)
        Case Is <> vbNullString
            Select Case Cells(i, 2)
                Case Is <> vbNullString
                    Cells(i, 1).EntireRow.Delete
            End Select
    End Select
Next i

End Sub

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