Reputation: 81
I'm trying to write code in C# to parse a large Excel sheet that wasn't really designed with automation in mind, and it's full of merged cells. Many times I know the location of one cell, but need to get the text of another cell a few cells away, but those cells may be merged and span multiple normal cells. How do I get the size of a merged cell in number of cells?
Also, how can I get the location of a cell a certain number of cells away, when the cells in between are merged? I tried Excel.Range.Offset, but that seems to be only counting real cells, not merged ones (so if there's a 4-wide merged cell in between, offset 2 will take me to the middle of that cell, rather than the one next to it).
Upvotes: 1
Views: 3287
Reputation: 748
You can use the following code to determine size of merged area:
var activeSheet = this.Application.ActiveSheet as Excel.Worksheet;
if (activeSheet != null)
{
var activeCell = activeSheet.Cells[2, 2];
if (activeCell.MergeCells)
{
if (activeCell.MergeArea != null)
{
dynamic mergeAreaValue2 = activeCell.MergeArea.Value2;
object[,] vals = mergeAreaValue2 as object[,];
if (vals != null)
{
int rows = vals.GetLength(0);
int cols = vals.GetLength(1);
}
}
}
}
Assumption is that Cells[2,2]
is left upper corner of merged area. In variables rows and cols will be the amount of rows and columns in merged area - so this is an answer to the question how many rows or columns should be skipped.
Upvotes: 2