In order to make a particular Excel workbook active from MATLAB, you will need to use the method ACTIVATE.
The following code is an example of how to use it. In this example MATLAB writes to an empty Excel file 'Book1.xlsm' which contains a macro named 'AddNew' that creates a new Excel file called 'test.xls'.
If the code is run, it is possible to see that first, the Excel file 'Book1.xlsm' is open and then, from MATLAB, the macro is run. This macro creates and opens the new Excel file 'test.xls', which becomes the active workbook. Then, to make 'Book1.xlsm' the active workbook, the command 'Workbook.Activate' is used. Finally, the code makes the second sheet active and writes on it, saves the workbook and closes Excel.
file = 'path_to_file\Book1.xlsm';
Excel = actxserver('Excel.Application');
Workbooks = Excel.Workbooks;
Excel.Visible = 1;
Workbook = Workbooks.Open(file);
Excel.Run('AddNew');
sheetnum=1;
data=rand(4);
range = 'F10:I13';
Workbook.Activate
Sheets = Excel.ActiveWorkBook.Sheets;
sheet2 = get(Sheets, 'Item', 2);
invoke(sheet2, 'Activate');
Activesheet = Excel.Activesheet;
ActivesheetRange = get(Activesheet,'Range',range);
set(ActivesheetRange, 'Value', data);
invoke(Workbook,'Save')
invoke(Excel,'Quit');
delete(Excel);
clear Excel;
Best Answer