Search code examples
excelvbadelete-row

Delete Row if populated with blanks and zeros within a range


I have a report where i need to remove the rows with no data in the cells or a zero within a range column C to O.

This code i have almost does it perfectly, but i found a fatal flaw in the logic. If the row has a positive and negative value that sum to zero it will be deleted while i would still need to retain that row.

I really appreciate the assistance from this site as I have been able to really automate many of my reports and help people in other departments! you guys rock! Thank You!

Dim rw As Long, i As Long
rw = Cells(Rows.Count, 1).End(xlUp).Row
For i = rw To 6 Step -1
If Application.Sum(Cells(i, 3).Resize(1, 17)) = 0 Then
Rows(i).Delete
End If
Next

Solution

  • Rather than checking the SUM, loop through each cell and check if its valid.

    To explain this better I will use pseudo code for you:

    1. Create a flag variable and set it to false
    2. Create a loop that will check each cell in a row
    3. If a valid number if found, set the flag to true
    4. Before moving to the next cell, check if your flag is still false
    5. If your flag is false -> Continue to next cell
    6. Loop through to the end of all of the cells in the row

    Pseudo-Code made into rough code

    Dim rw As Long, i As Long
    Dim rng As Range
    Dim validRow As Boolean
    validRow = false
    
    rw = Cells(Rows.Count, 1).End(xlUp).Row
    
    For i = rw To 6 Step -1
        Set rng = (Cells(i, 3).Resize(1, 17))
        For Each cell In rng
             If Not IsEmpty(cell) Then
                If cell.value <> 0 Then
                   validRow = true
                End If
             End If
             If validRow = true Then
            Exit For
             End If
        Next cell
        If validRow = false Then
            Rows(i).Delete
        End If
        validRow = false
    Next
    

    [@LL edit: changed >0 to <>0 too look for anything different than zero, to account for rows populated with only negative values]