Search code examples
c#exceloffice-interop

Getting HRESULT error when assigning Excel range?


I'm writing a basic program to manipulate Excel using C#, and I'm having trouble assigning a range. Here's my code:

using Excel = Microsoft.Office.Interop.Excel;
//...various other using statements

static void Main(string[] args)
        {
            Excel.Application xlApp = new Excel.Application();
            xlApp.Visible = true;
            Excel.Workbook bk=xlApp.Workbooks.Add();
            Excel.Worksheet sht = bk.Sheets["Sheet1"];
            Excel.Range rng;
            for (int c = 0; c < 10;c++ )
            {

                rng=sht.Cells[c,1];
                rng.Value= "aaa";
            }

        }

I keep getting the following error on the rng=sht.Cells[c,1]; line:

An unhandled exception of type
'System.Runtime.InteropServices.COMException' occurred in mscorlib.dll

Additional information: Exception from HRESULT: 0x800A03EC

Solution

  • The first index to Cells will be 0 at the start of the look which XL does not like. Start from 1.