How do I access a cell in Excel Interop when using filtered ranges?

帅比萌擦擦* 提交于 2020-01-16 14:53:10

问题


I originally had a code segment that iterated through rows of an Excel spreadsheet using the UsedRange as such:

           range = ws.UsedRange;
           for (int row = 3; row <= range.Rows.Count; row++)
            {
                Object nObj = ((Excel.Range)ws.Cells[row, "N"]).Text;
            }

But I needed to only get the rows that remained after I applied a filter so (after viewing How can I get the Range of filtered rows using Excel Interop?) I changed the code as such:

    range = ws.UsedRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible, Type.Missing);
    foreach (Excel.Range area in range.Areas)
    {
        foreach (Excel.Range row in area.Rows)
            //for (int row = 3; row <= range.Rows.Count; row++)
            {
                Object nObj = ((Excel.Range)ws.Cells[row, "N"]).Text;
            }
    }

Except now I'm getting type mismatch errors. What fundamental thing am I missing here?


回答1:


I believe you are getting a type mismatch at the call to ws.Cells[row, "N"]. In the original code, row is an int. In the modified code, row is an Excel.Range.

Given that, in the modified code, row is a single row (multiple column) range, all you should need to do is index into the cell in that row which corresponds to column N. Assuming your range starts in column A, this will be the cell in 14th column.

E.g.

Object nObj = ((Excel.Range)row.Cells[1, 14]).Text;


来源:https://stackoverflow.com/questions/8467167/how-do-i-access-a-cell-in-excel-interop-when-using-filtered-ranges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!