Michael
Michael

Reputation: 123

Naming excel sheets using list C#

I am trying to create 12 new worksheets in an excel workbook. I would then like to change the name of each sheet to be the name of a month (January - December).

Code:

List<string> Months = new List<string> { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
for (int i = 0; i < Months.Count; i++)
            {
                Microsoft.Office.Interop.Excel.Worksheet "sheet" + i = (Worksheet)xlApp.Worksheets["Sheet" + (i+1)];
                "sheet" + i.Name = Months[i];
            }

As for the variable names of the sheets, I would like to name each worksheet "sheet" + i (a number 0-11).

A full example would look like this...

Microsoft.Office.Interop.Excel.Worksheet sheet0 = (Worksheet)xlApp.Worksheets["Sheet1"];
            sheet0.Name = "Jan";

Everything works fine besides the variable naming ("sheet" + i). Any suggestions?

Upvotes: 1

Views: 230

Answers (2)

gravity
gravity

Reputation: 2056

I can confirm that this worked for me successfully, after a quick validation against what you wanted from the comments:

List<string> Months = new List<string> { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

Application xlApp = new Application();
Workbook bkMonths = xlApp.Workbooks.Add();
xlApp.Visible = true;

for (int i = 0; i < Months.Count; i++)
{
    Worksheet sheetCurrent = xlApp.Worksheets.Add();
    sheetCurrent.Name = Months[i];
}

Upvotes: 2

quetzalcoatl
quetzalcoatl

Reputation: 33506

In your code, you have:

Microsoft.Office.Interop.Excel.Worksheet "sheet" + i = (.....)
"sheet" + i.Name = Months[i];

In the example they indeed used a variable called sheet0, but you don't need to follow it so strictly. A variable can have any name like mySheet or nextSheet.

You don't need to try "build" a numbered variable name like "sheet"+i. Even more, that will simply not work. Please note that sheet0 is a complete variable name. The 0 is part of the name, there are no " (quotes) and no "adding" a number to the variable name. You cannot "create" new variables in such way.

Instead, just pick any normal name:

for(....)
{
    Microsoft.Office.Interop.Excel.Worksheet justOneOfTheSheetsAtTime = (.....)
    justOneOfTheSheetsAtTime.Name = Months[i];
}

It doesn't matter that it is inside a loop. Each time the loop iterates, the same variable name wil be used and a different sheet will be put into it. There is no problem with using a single variable to inspect&change a hundred of sheets through a loop.

Upvotes: 3

Related Questions