This is a follow-up question to an old question:
How to get the range of occupied cells in excel sheet
Quoting from that question:
Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = sheet.get_Range("A1", last);
"range" will now be the occupied cell range share|improve this answer answered Aug 18 '09 at 9:03 Zurb
it returns always time blank cells, which i think question author wants to "not to get" that blank cells.– JavidanApr 23 at 7:30
See the Range.SpecialCells method. For example, to get cells with constant values or formulas use:
_xlWorksheet.UsedRange.SpecialCells(
Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeConstants |
Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeFormulas)
share|improve this answer answered Aug 16 '09 at 14:23 Joe Erickson
Back to my question...
I tried to use this method which generates this exception:
System.Runtime.InteropServices.COMException: 'SpecialCells method of Range class failed'
Here is my code:
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
Excel.Application xlapp = new Excel.Application();
Excel.Workbook wbook = xlapp.Workbooks.Open(tbxFilename.Text);
Excel.Worksheet wsheet = wbook.Sheets[1];
Excel.Range range = wsheet.UsedRange;
tbxOutput.AppendText($"UsedRange: Rows = {range.Rows.Count}, Cols `enter code here`= {range.Columns.Count}\r\n");
range = wsheet.UsedRange.SpecialCells(Excel.XlCellType.xlCellTypeConstants | // generates Exception
Excel.XlCellType.xlCellTypeFormulas, Missing.Value);
tbxOutput.AppendText($"Rows = {range.Rows.Count}, Cols = {range.Columns.Count}\r\n");
What is wrong with my code? Thanks!