Note that there are some explanatory texts on larger screens.

plurals
  1. POExcel Interop - Add a new worksheet after all of the others
    text
    copied!<p>I am trying to add a new worksheet to an Excel workbook and make this the last worksheet in the book in C# Excel Interop.</p> <p>It seems really simple, and I thought the below code would do it:</p> <pre><code>using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var excel = new Excel.Application(); var workbook = excel.Workbooks.Open(@"C:\test\Test.xlsx"); workbook.Sheets.Add(After: workbook.Sheets.Count); workbook.Save(); workbook.Close(); Marshal.ReleaseComObject(excel); } } } </code></pre> <p>No such luck. I get this helpful error:</p> <blockquote> <p>COMException was unhandled - Exception from HRESULT: 0x800A03EC</p> </blockquote> <p>I found <a href="http://support.microsoft.com/kb/107622" rel="noreferrer">this page</a> on Microsoft.com which suggested I try and add the sheet first and then move it so I tried that as shown below. I know that this webpage targets Excel 95 but the VBA is still there to use so I was hoping it would still work:</p> <pre><code>using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { var excel = new Excel.Application(); var workbook = excel.Workbooks.Open(@"C:\test\Test.xlsx"); workbook.Sheets.Add(); workbook.Sheets.Move(After: workbook.Sheets.Count); workbook.Save(); workbook.Close(); Marshal.ReleaseComObject(excel); } } } </code></pre> <p>I get the same error as above. I have also tried passing the name of my last worksheet as a string as the <code>After</code> parameter in both the <code>Add</code> and <code>Move</code> methods, no joy!</p> <p>That is what I have tried, so my question is how do I add a worksheet to an Excel workbook and make this the last sheet in the workbook using C# Excel Interop?</p> <p>Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload