0

I try to read a cell in an Excel worksheet using Excel Interop 15.0. At start my code look like this and it worked

Range myvar = (Worksheet.Cells[1,1]) as Range

For some unknown reasons, this code doesn't work anymore and I need to use

Range myvar = Worksheet.Cells[1,1]

Also, the code below thrown an InvalidCastException

Range myvar = (Range)(Worksheet.Cells[1,1])

Can someone tell me why the first code worked at start and now fails? And why the last example throws an exception ?

[Update - 2017-05-27 09:42]

Weird, here, my code:

if (!string.IsNullOrWhiteSpace((pBlueBookWorksheet.Cells[pBlueBookWorksheet.Range[aSetting.BlueBookCodeCellName].Row, i] as Range).Value.ToString()))
                        lCodeIndex.Add(Convert.ToString((pBlueBookWorksheet.Cells[pBlueBookWorksheet.Range[aSetting.BlueBookCodeCellName].Row, i] as Range).Value), i);  

Yesterday and this morning before I try it didn't work. So I start removing 'as Range' but I noticed that some lines with 'as Range' work but some others don't. So, I decide to use 'as Range' again and MIRACLE, the program works ?!? It's as if writing the line again changed something in background. Oh also, lat night, I installed VS2017 Update 2

So If someone has an explanation to this phenomenon, send it

Thanks

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
sylvain
  • 9
  • 2
  • which excel component have you used, office interop, aspose or any others? the `as` will return null(do not throw exception) when cast failed. ref : [Casting vs using the 'as' keyword in the CLR](https://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr) – aspark May 27 '17 at 06:39
  • I'm using Interop. About the fact 'as' return null instead of exception, I know that. But why the last example throws an exception if the Cells property return a Range ? – sylvain May 27 '17 at 10:56
  • i can not reproduce this problem with your code. the only thing i can think of is that there is another class with the same name – aspark May 28 '17 at 01:54

0 Answers0