7

currently i'm doing this:

string cellValue = sheet.get_Range("A12", _missing).Value2.ToString();

this works but i really need to select a cell by row and column index.

i get a null exception when i try

string cellValue = ((Range)sheet.Cells[row, column]).Value2.ToString();

any ideas?

CurlyFro
  • 1,862
  • 4
  • 22
  • 39
  • possible duplicate of [How do I get an Excel range using row and column numbers in VSTO / C#?](http://stackoverflow.com/questions/2333202/how-do-i-get-an-excel-range-using-row-and-column-numbers-in-vsto-c) – nawfal Jan 05 '14 at 06:37

2 Answers2

8

Where does the ArgumentNullException occur? Try separating out your code like this and step through it:

object rangeObject = sheet.Cells[row, column];
Range range = (Range)rangeObject;
object rangeValue = range.Value2;
string cellValue = rangeValue.ToString();

This will show you where the null object is.

Zach Johnson
  • 23,678
  • 6
  • 69
  • 86
  • the NullReferenceException happens at string cellValue = rangeValue.ToString(); because range.Value2 is null. i know my sheet is good but i think sheet.Cells[row, column] is the real culprit. – CurlyFro Feb 19 '10 at 21:40
  • I think then, that a null `range.Value2` indicates that the cell does not have a value. If you look at the cell in Excel, is it empty? – Zach Johnson Feb 19 '10 at 21:46
  • 2
    Also, Excel interop uses 1-based indexing. The problem could be that you are using zero-based indexes which reference an empty cell. If that is the case, then all you need to do is use `row + 1` and `column + 1` to get the correct cell. – Zach Johnson Feb 19 '10 at 21:50
  • also you can try using get_value instead of Value2 – Stan R. Feb 19 '10 at 21:53
0

I had the same issue. The nullref would happen when the cell I was reading was empty.

string foo = (((Range) ActiveWorksheet.Cells[row, column]).Value2 != null
            ? ((Range) ActiveWorksheet.Cells[row, column]).Value2.ToString()
            : "Coalesce some false string here..."); 

Notice that you have to check for null before you attempt to transform or cast the value.

Joe Johnston
  • 2,794
  • 2
  • 31
  • 54