View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
craigd craigd is offline
external usenet poster
 
Posts: 2
Default Looping in Excel XP with C# -- Ranges and SpecialCells

Jan, *thanks* for the quick reply.

The specialcells method may return a collection of areas (non-contiguous
ranges) which each contain a collection of cells. You must therefore
loop through the cells in each area separately.


You are correct - I didn't understand that from the documentation.

The following code (looping through SpecialCells:Areas:Ranges:Cells
rather than ALL the UsedRange cells) reduced the 'processing time' for
my test spreadsheet from 90 minutes to under 3 minutes!

Excel.Range newrange =
range.SpecialCells(Microsoft.Office.Interop.Excel. XlCellType.xlCellTypeConstants,
(object)3 );
for (int areaid = 1; areaid <= newrange.Areas.Count; areaid++){
Excel.Range arearange = newrange.Areas.get_Item(areaid);
for (int row = 1; row <= arearange.Rows.Count; row++){
for (int col = 1; col <= arearange.Columns.Count; col++){
cell = (Excel.Range)arearange.Cells[row, col];
// do stuff with cell.Value2
}
}
}

My test doc (which is intentionally quite complex) doesn't approach
the 8192-range-limit; if that happens in production then we've
probably got other problems too!

Thanks again