Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I am trying to count the no. of rows in the used range of an excel sheet

My code is as follow
int lastrow1;
string path = textBox1.Text;
                    string path1 = textBox2.Text;
                    string Filename = path.Substring(path.LastIndexOf('\\') + 1);
                    string Filename1 = path1.Substring(path.LastIndexOf('\\') + 1);
                    Microsoft.Office.Interop.Excel.Application ExcelObj = new Microsoft.Office.Interop.Excel.Application();
                    Microsoft.Office.Interop.Excel.Workbook theWorkbook = ExcelObj.Workbooks.Open(path, 0, true,6, "", "",false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "|", true, false, 0, true, false, false);
                    Microsoft.Office.Interop.Excel.Sheets sheets = theWorkbook.Worksheets;
                    Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(1);
                    lastrow1 = (Microsoft.Office.Interop.Excel.Range)workSheet.UsedRange.Rows.Count;

At this point i get an error.
"Cannot convert type int to microsoft.office.interop.excel.range"

Please help
Posted
Updated 20-Apr-11 20:47pm
v2

You declare lastRow1 to be an int, and then you try to explicitly cast it to a Excel Range

C#
lastrow1 = (Microsoft.Office.Interop.Excel.Range)workSheet.UsedRange.Rows.Count;


Surely you can see the error here. The error is telling you exactly what is wrong. Seriously - read the error.
 
Share this answer
 
There is no need to cast it to type Range. Remove the cast.
This will do :

C#
lastrow1 = workSheet.UsedRange.Rows.Count;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900