Search code examples
excelhiderowsskipvba

How can I Hide Excel rows if SUM of contents = zero and skip blanks?


I have two codes, below, one that hides and the other that unhides rows based on the sum of values contained therein equaling zero. However, this code also hides blank rows which I do not want since they are spacers between sections. Any advice would be apprecated, and if there are recommendations to improve the existing code I would appreciate that as well.

Sub HideRows()

Dim R As Long
Dim Rng As Range

    If Selection.Rows.Count > 1 Then
        Set Rng = Selection
    Else
        Set Rng = ActiveSheet.UsedRange
    End If

    For R = 1 To Rng.Rows.Count
        If Application.Sum(Range(Rng(R, 3), Rng(R, Rng.Columns.Count))) = 0# Then
        Rng.Rows(R).Hidden = True
        End If
    Next R

End Sub
Sub UnHideRows()

Dim R As Long
Dim Rng As Range

    If Selection.Rows.Count > 1 Then
        Set Rng = Selection
    Else
        Set Rng = ActiveSheet.UsedRange
    End If

    For R = 1 To Rng.Rows.Count
        If Application.Sum(Range(Rng(R, 3), Rng(R, Rng.Columns.Count))) = 0# Then
        Rng.Rows(R).Hidden = False
        End If
    Next R

End Sub

Solution

  • replace the FOR loop in each method with this....

    myRange = Range(Rng(R, 3), Rng(R, Rng.Columns.Count))
    For R = 1 To Rng.Rows.Count
      If Application.CountBlank(myRange) <> myRange.Cells.Count Then
        If Application.Sum(myRange) = 0# Then
          Rng.Rows(R).Hidden = True
        End If
    Next R
    

    It first checks to see if all the cells in that row range are blank and essentially skips further processing if true.