0

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?

2
Contributors
2
Replies
14
Views
4 Years
Discussion Span
Last Post by spowel4
0

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.

0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.