This project has moved. For the latest updates, please go here.

How does one iterate over all rows/columns in an ExcelNamedRange?

Jan 16, 2012 at 2:10 PM

Hi,

I have the following code, but I receive an exception in the outer for loop on the ExcelNamedRange Start and End properties.

The exception thrown is:

System.ArgumentOutOfRangeException : Row cannot be less then 1.
Parameter name: value

Can somebody provide a clear overview on how to work with named ranges?

Best regards,

Fab

ExcelWorksheet sheet = _openXmlPackage.Workbook.Worksheets["SheetName"];
           
using (ExcelNamedRange namedRange = sheet.Names["RangeName"])
{
    for (int rowIndex = namedRange.Start.Row; rowIndex <= namedRange.End.Row; rowIndex++)
    {
        for (int columnIndex = namedRange.Start.Column; columnIndex <= namedRange.End.Column; columnIndex++)
        {
            var test = sheet.Cells[rowIndex, columnIndex].GetValue<String>();
        }
    }
}

 


Coordinator
Jan 31, 2012 at 5:59 PM

If the name reference an range in a worksheet, you should be able to use a foreach to access the cells.

If the cell reference a value, formula or external reference this will NOT work. Is that the case here?

Jan

Feb 3, 2012 at 4:43 AM
Edited Feb 3, 2012 at 4:45 AM

-deleted-