MATLAB: How to rename a sheet in Excel using the COM interface in MATLAB

activeactivexMATLABserverspreadsheetx

I am using ACTXSERVER to control Excel. I have the following code to open a document, and I would like to rename an existing sheet in the workbook.
filename = 'C:\SomeExcelFile.xls';
% Open Excel Automation server
Excel = actxserver('Excel.Application');
% Make Excel visible
Excel.Visible=1;
% Open Excel file
Workbook = Excel.Workbooks.Open(filename);
% Get the list of sheets in the workbook
Sheets = Excel.ActiveWorkbook.Sheets;

Best Answer

You can rename an Excel sheet using the "Name" property of a sheet object. For example the following renames the first sheet of an Excel file:
filename = 'C:\SomeExcelFile.xls';
% Open Excel Automation server
Excel = actxserver('Excel.Application');
% Make Excel visible
Excel.Visible=1;
% Open Excel file
Workbook = Excel.Workbooks.Open(filename);
% Get the list of sheets in the workbook
Sheets = Excel.ActiveWorkbook.Sheets;
% Rename the first sheet
Sheets.Item(1).Name = 'This is sheet 1';
The following code then saves the Workbook, quits Excel and removes the COM server:
% Save the file
Workbook.Save();
% Quit Excel, remove the COM server and delete the related objects
Excel.Quit();
Excel.delete();
clear Excel;
clear Workbook;
clear Sheets;