Worksheet get_Range throws exception

Viewed 50295

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?

5 Answers

I tried the above answers on .NET 5 but they do not work anymore. Instead, following code works.

Excel.Range c1 = (Excel.Range)excelSheet.Cells[1, 1];
Excel.Range c2 = (Excel.Range)excelSheet.Cells[4, 4];
Excel.Range oRange = oSheet.get_Range(c1, c2);
  
Related