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.
This works:
oRange = (Excel.Range)oSheet.get_Range("A1","F1");
oRange.EntireColumn.AutoFit();
This throws an exception:
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'
The oSheet is instantiated as follows:
Excel.Worksheet oSheet = new Excel.Worksheet();
Am I supposed to instantiate both differently?
It looks like the exception is thrown from the
oSheet.Cells[1, 1]andoSheet.Cells[4, 4]used as arguments toget_range.Applying the following, no exception will be thrown:
So, it might be related to the
oSheet.get_Rangefunctionality. It receives an object as an argument, therefore it might try to invoke aget_Rangemethod on the arguments to receive the internal cell, and the up-cast fromRangeto object done by the compiler might hide the method call.If you need the cells definition by row/column – try using the above approach.