使用过滤范围时,如何在Excel Interop中访问单元格? [英] How do I access a cell in Excel Interop when using filtered ranges?

查看:202
本文介绍了使用过滤范围时,如何在Excel Interop中访问单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最初有一个代码段,它使用UsedRange这样迭代Excel电子表格的行:

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

但是,我需要只得到我应用过滤器后剩下的行(在查看之后查看)过滤行的范围使用Excel Interop?)我更改了代码:

  range = ws.UsedRange。 SpecialCells(Excel.XlCellType.xlCellTypeVisible,Type.Missing); 
foreach(range.Areas中的Excel.Range区域)
{
foreach(area.Rows中的Excel.Range行)
// for(int row = 3; row< ; = range.Rows.Count; row ++)
{
对象nObj =((Excel.Range)ws.Cells [row,N])。
}
}

除了现在我得到类型不匹配错误。我在这里缺少什么基本的东西?

解决方案

我相信你在调用 ws.Cells [row,N] 。在原始代码中,是一个 int 。在修改后的代码中,是一个 Excel.Range



在修改后的代码中, row 是单行(多列)范围,所有您需要做的就是索引到该行中的单元格对应于列N.假设您的范围从A列开始,这将是第14列中的单元格。



例如

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


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?

解决方案

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;

这篇关于使用过滤范围时,如何在Excel Interop中访问单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆