I am new to VSTO C# excel add-in. I am looking to find total count of not null/empty rows in a range. My Code looks at the range "A4:E4" and count total number of rows.
This is the code :
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Workbook workbook = Globals.ThisAddIn.GetWorkBook("c:\\temp\\testfile.xlsx");
Worksheet mergeSheet = workbook.Worksheets["Data"];
Excel.Range mergeCells = mergeSheet.Range["A4:E4"];
var colValues = (System.Array)mergeCells.Columns[1].Cells.Value;
var strArray = colValues.OfType<object>().Select(o => o.ToString()).ToArray();
var rowCount = strArray.Length;
}
[public Excel.Workbook GetWorkBook(string pathName)
{
return (Excel.Workbook)Application.Workbooks.Open(pathName);
}][1]
I get error var colValues = (System.Array)mergeCells.Columns[1].Cells.Value;on line :
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot convert type 'string' to 'System.Array''
It works when I have two rows in my range. I have hardcoded range A4:E4 to produce the error. My excel sheet (testfile.xlsx) looks like below:
Any ideas how do I resolve this?
Same line of code works when I have two rows. Eg and following line is updated
Excel.Range mergeCells = mergeSheet.Range["A4:E5"];



mergeCells.Columns[1].Cells.Value) instead of all the columns in your range (mergeCells.Cells.Value). There is a working sample in another question, so I have taken the liberty to link the other question as a duplicate.