MATLAB: Delete sheet number 1 in excel

activexexcel

I want to delete sheet number 1 in excel. Here is the code I wrote:
newExcel = actxserver('excel.application');
excelWB = newExcel.Workbooks.Open(filepath,0,false);
newExcel.Sheets.Item(1).Delete;
excelWB.Save();
excelWB.Close();
newExcel.Quit();
delete(newExcel);
Can anyone help me to solve this issue.

Best Answer

The problem is that by default Excel asks you to confirm that you really want to delete the worksheet. As excel is not visible, you don't see the confirmation dialog (a bit daft, I know!). You can verify this for yourself, by issuing:
newExcel.Visible = true;
before your delete command.
To fix your issue, simply tells excel to not display alerts with:
newExcel.DisplayAlerts = false;
before trying to delete the sheet.
Finally, instead of
newExcel.Sheets.Item(1).Delete;
I would use
excelWB.Sheets.Item(1).Delete;
The former delete a sheet in the active workbook, the later always in excelWB. The active workbook is most likely excelWB as you've just opened it, but it's always better to be explicit.