1

I have sheet where the "heading" are in merged cells and the value is in the cells under the "heading", see example.

How can I count how many cells the heading spans? I need this to know where to start and stop reading the cells that belong to the "heading".

+-----------+-----------+
|  Heading1 | Heading2  |
+-----------+-----------+
| 1 | 2 | 3 | 3 | 3 | 4 |
+---+---+---+---+---+---+
| 4 | 5 | 6 | 3 | 3 | 3 |
+---+---+---+---+---+---+
Charlie Clark
  • 18,477
  • 4
  • 49
  • 55
The Dude
  • 1,088
  • 7
  • 16
  • 30

2 Answers2

-1

You could use a function in VBA in Excel, like below

Public Function COLUMNSINMERGED(r As Excel.Range)

If r.MergeCells Then
    COLUMNSINMERGED=r.MergeArea.Columns.Count
    Debug.Print r.MergeArea.Address, "Cols : " & r.MergeArea.Columns.Count, "Rows : " & r.MergeArea.Rows.Count
else
   COLUMNSINMERGED=r.cells.count      
End If

End Function
Nathan_Sav
  • 8,466
  • 2
  • 13
  • 20
-1

You can get the convertLetterToColumnNum function from Excel Column Number to Text

#calculates the span given a merged cell
#first checks to see if cell is merged and then calculates the span
def calculateSpan(sheet, cell):
    idx = cell.coordinate
    for range_ in sheet.merged_cell_ranges:
        merged_cells = list(openpyxl.utils.rows_from_range(range_))
        for row in merged_cells:
            if idx in row:
                # If this is a merged cell
                first_col=convertLetterToColumnNum(str(merged_cells[0][0][0]))
                second_col = convertLetterToColumnNum(str(merged_cells[0][1][0]))
                span=abs(second_col-first_col)+1 #remove +1 if you want to count from zero
                return span

#usage
print(calculateSpan(mysheet,mysheet['D11']))

The rest is a modified version of How do i get value present in a merged cell

Boikem
  • 39
  • 11