Home » excel » Excel count rows while treating merged rows as one

Excel count rows while treating merged rows as one

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to count rows in a spreadsheet with merged rows. By default, excel’s ROWS function counts every individual cell but I need a function to treat merged cells as a single row.

How to&Answers:

VBA script seems to be the only way to do this. Below is a rough example that works (though likely fails in corner cases dealing with multiple columns):

Public Function MergedRowsCount(r As Range) As Long
    MergedRowCount = 0
    For i = 1 To r.Rows.Count
        MergeRowSize = r(i).MergeArea.Rows.Count
        If MergeRowSize > 1 Then
            i = i + MergeRowSize - 1
        End If
        MergedRowCount = MergedRowCount + 1
    Next i
    MergedRowsCount = MergedRowCount
End Function

enter image description here

Answer:

This may help you:

Code:

Option Explicit

Sub test()

    Dim rng As Range, cell As Range
    Dim mrgCells As Long, UnmrgCells As Long, TotalCells As Long, mrgRows As Long, mrgColumns As Long, i As Long

    With ThisWorkbook.Worksheets("Sheet1")

        Set rng = .Range("A1:B10")

        'Total number of cells in a range(DOES NOT includes merge cells)
        TotalCells = rng.Cells.Count

        UnmrgCells = 0
        mrgColumns = 0
        mrgRows = 0

        For Each cell In rng

            If cell.MergeCells Then
                mrgCells = mrgCells + 1
            Else
                UnmrgCells = UnmrgCells + 1
            End If

        Next cell

        For i = 1 To 10

            If .Range("A" & i).MergeArea.Rows.Count > 1 Then
                mrgRows = mrgRows + 1
            End If

            If .Range("A" & i).MergeArea.Columns.Count > 1 Then
                mrgColumns = mrgColumns + 1
            End If

        Next i

        Debug.Print "Total Number of Cells: " & TotalCells & vbNewLine & _
                    "Total Number of Merged Cells: " & mrgCells & vbNewLine & _
                    "Total Number of Merged Rows: " & mrgRows & vbNewLine & _
                    "Total Number of Merged Columns: " & mrgRows & vbNewLine & _
                    "Total Number of Non Merged cells: " & UnmrgCells

    End With

End Sub

Results:

enter image description here