细胞与#REF!用于获取多单元格范围时,错误会导致COM异常

时间:2013-06-01 05:26:58

标签: c# excel com

我有一行数据,下面有一行单元格,都有#REF!错误。我想使用以下内容将数据行向下拖动到错误行上:

Excel.Range topLeft=ReportSheet.Cells[1,1];
Excel.Range topRight=ReportSheet.Cells[1,10];
Excel.Range bottomRight=ReportSheet.Cells[3,10];
Excel.Range sourceRange = ReportSheet.Cells[topLeft, topRight];
Excel.Range targetRange = ReportSheet.Cells[topLeft, bottomRight];
sourceRange.AutoFill(targetRange);

sourceRange被分配没有问题,但是分配targetRange(包括带有#REF!错误的行)会引发COM异常:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Exception from HRESULT: 0x800A03EC

关于如何避免此异常的任何想法?

更新:我尝试删除#REF!尝试执行自动填充之前的行。同样的错误。 sourceRange.AutoFill可以在数据下方没有错误行的测试数据上正常工作。

2 个答案:

答案 0 :(得分:0)

Excel.Range temp1 =ReportSheet.Cells[1,1];
Excel.Range temp2 =ReportSheet.Cells[1,2];
Excel.Range temp3 =ReportSheet.Cells[1,20];
Excel.Range sourceRange = ReportSheet.Cells[temp1 , temp2 ];
Excel.Range targetRange = ReportSheet.Cells[temp1 , temp3];
sourceRange.AutoFill(targetRange);

尝试上面它会起作用。

自动填充的目的地必须包含来源范围。

答案 1 :(得分:0)

我已经解决了这个问题。有两个问题:

  • 设置targetRange需要使用ReportSheet.Range代替ReportSheet.Cells
  • AutoFill只能一维工作,即一行填充其他行或列填充其他列。我认为,我的原始代码失败了,因为将targetRange设置为Range[topLeft,bottomRight]意味着AutoFill必须填写正确。

修订后的工作代码是:

Excel.Range topLeft=ReportSheet.Cells[1,1];
Excel.Range bottomLeft=ReportSheet.Cells[3,1];
Excel.Range topRight=ReportSheet.Cells[1,10];
Excel.Range bottomRight=ReportSheet.Cells[3,10];
Excel.Range topRow=ReportSheet.Range[topLeft,topRight];
Excel.Range bottomRow=ReportSheet.Range[bottomLeft,bottomRight];
Excel.Range targetRange=ReportSheet.Range[topRow,bottomRow];
topRow.AutoFill(targetRange);

我从this answer获得了线索。