I am trying to set the value of cells in an Office 2010 worksheet using this code in Visual Studio 2012:

for (int i = 1; i < 5; i++)
{
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(i);
    int columnCounter = 1;
    foreach (string s in columnNames)
    {
        range = ((Excel.Range)xlWorkSheet.Cells[1, columnCounter]);
        range.Value = s;
        columnCounter++;
    }
}

While stepping through this code it fails every time at the range.Value = s; line and goes immediately to another method that closes Excel. It does not give any error messages and so I am lost as to why this isn't working. Can someone please help?

I have this method and it works fine with me:

public void PutData(int row, int col, string data)
        {
            worksheet.Cells[row, col] = data;
        }

Also keep in mind that Cells is a Range object.

Thank you ddanbe, I used a slightly modified version of your method:

        private void FillCell(int columnCounter, string s)
        {
            range = ((Excel.Range)xlWorkSheet.Cells[1, columnCounter]);
            range.Value = s;
        }

and it seems to be working. I couldn't get your method to work verbatim, it kept bombing out on the xlWorkSheet.Cells[1, columnCounter] = s line.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.