tags:

views:

314

answers:

2

Why does this work:

((Excel.Worksheet)Application.ActiveSheet).get_Range("A1", "A1").Value2 = text;

But this doesn't:

Excel.Worksheet activeSheet = ((Excel.Worksheet)Application.ActiveSheet);
activeSheet.Cells[0, 0] = text;

I need to do it the second way as I need to loop with rowIndex and colIndex. How can I do that?

I get the error:

An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll Additional information: Exception from HRESULT: 0x800A03EC

A: 

Crap .. because it's not zero based!!!

+1  A: 

The only thing you're missing (other than using 1 based indexes) is to cast the cell reference to a range explicitly:

Excel.Worksheet activeSheet = ((Excel.Worksheet)Application.ActiveSheet);
int endRow = 5;
int endCol = 6;

for(int idxRow = 1; idxRow <= endRow; idxRow++)
{
    for(int idxCol = 1; idxCol <= endCol; idxCol)
    {
        ((Excel.Range)activeSheet.Cells[idxRow, idxCol]).Value2 = "Kilroy wuz here";
    }
}
Paul Keister