工作表get_Range抛出异常 [英] Worksheet get_Range throws exception
问题描述
我使用C#来操作一个Excel工作表。下面的代码两件应该工作一样,但一期工程和其他抛出异常。我不知道为什么。
I'm using C# to manipulate an Excel worksheet. The following two pieces of code should work the same, but one works and the other throws an exception. I wonder why.
本作品:
oRange = (Excel.Range)oSheet.get_Range("A1","F1");
oRange.EntireColumn.AutoFit();
这将引发异常:
oRange = (Excel.Range)oSheet.get_Range(oSheet.Cells[1, 1],oSheet.Cells[4,4]);
oRange.EntireColumn.AutoFit();
例外:
Exception:
RuntimeBinderException occurred. "object" does not contain a definition for 'get_Range'
的
oSheet
如下实例:
Excel.Worksheet oSheet = new Excel.Worksheet();
我应该实例化两个不同?
Am I supposed to instantiate both differently?
推荐答案
看起来异常是从oSheet.Cells抛出[1,1]和oSheet.Cells [4,4]作为参数get_range。
it looks like the exception is thrown from the oSheet.Cells[1, 1] and oSheet.Cells[4, 4] used as arguments to get_range.
通过执行以下,没有异常:
by doing the following, there is no exception:
Excel.Range c1 = oSheet.Cells[1, 1];
Excel.Range c2 = oSheet.Cells[4, 4];
oRange = (Excel.Range)oSheet.get_Range(c1, c2);
oRange.EntireColumn.AutoFit();
所以它可能会涉及到oSheet.get_Range功能。它接收对象作为参数,因此它可能会尝试调用的参数的get_Range方法接收内部的细胞,并从范围向上投对象由编译器完成可能会隐藏在方法调用。
so it might be related to the oSheet.get_Range functionality. It receives object as argument, therefore it might try to invoke a get_Range method on the arguments to receive the internal cell, and the up-cast from Range to object done by the compiler might hide the method call.
如果你需要行/列的单元定义 - 尝试使用上面的方法
if you need the cells definition by row/column - try using the above approach
这篇关于工作表get_Range抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!