title: How to properly copy an Excel worksheet with Office interop?
body: <p>i want in a loop to copy worksheets in excel, modify them and save the Excel file. I use C#, Excel through COM. I have read this example: <a href="https://stackoverflow.com/questions/3066603/opening-ms-excel-worksheet-in-c-sharp">Opening MS Excel worksheet in C#</a></p>
  
  <p>I have a "source" worksheet. I want in a loop copy that source worksheet, modify 3 cells, change the name and append after the source worksheet.</p>
  
  <p>My problem is that on the second iteration the source worksheet isnt there. In this example "1.Babimost-miasto". It says: Index not found. I guess he has copied it to "1.Babimost-miasto (2)". But what i'n doing wrong and how can i achieve this?</p>
  
  <pre><code>//Get a new workbook.
  //oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
  oWB = (Excel._Workbook)(oXL.Workbooks.Open(outputFilePath));
  
  //this is source
  oSheet = (Excel.Worksheet)oWB.Worksheets["1.Babimost-miasto"];
  //oSheet.Copy(Type.Missing, oSheet);
  
  for (int i = 0; i &lt; 5; i++)
  {
      //i want a copy
      Excel._Worksheet oSheetCopy = (Excel._Worksheet)oWB.Worksheets["1.Babimost-miasto"];
      //give this copy a new name
      oSheetCopy.Name = (input[i] as OrderedDictionary)[KEY_CITY].ToString();
      //modify in the copy some cells
      oSheetCopy.Cells[1, 1].Value = (input[i] as OrderedDictionary)[KEY_CITY]; //A1
      oSheetCopy.Cells[5, 4].Value = (input[i] as OrderedDictionary)[KEY_2010]; //D5
      oSheetCopy.Cells[45, 2].Value = (input[i] as OrderedDictionary)[KEY_1995]; //B45
  
      //((Excel._Worksheet)oWB.Sheets["MyTemplate"]).Delete(); // delete template
      //copy the copy after my source worksheet
      oSheetCopy.Copy(Type.Missing, oSheet);
      ((Excel._Worksheet)oWB.Worksheets[(input[0] as OrderedDictionary)[KEY_CITY].ToString()]).Activate();
  }
  
  oXL.UserControl = false;
  oXL.DisplayAlerts = false;
  oWB.Save();
  </code></pre>