MATLAB: Exporting from Matlab to excel with macro.

excelmacroMATLAB

I have matrix which I have to add in excel file. Excel file looks like in picture. With StartLoft, than StartCurve, than matrix which needs to be added, than EndCurve, EndLoft, End.
In this excel I should have embedded macro file to just open excel after starting matlab code, and run macro, without adding it additionaly. Is this possible? Macro code for excel is attached.

Best Answer

My advice would be to have a blank excel file that already has the macro code in it. Whenever you want to create a new file with that macro, just copy that template file and fill it with xlswrite. This is probably the easiest and most reliable way.
Otherwise, yes it is possible to insert the macro from matlab, with some restrictions. The first problem you'll face is that for many versions now, Microsoft, by default, forbids programmatic access to VB projects (where macro code resides). The only way to enable programmatic access is within excel itself, under the Macro Settings of the Trust Center (in options), you need to tick Trust access to the VBA project object model. This cannot be done programmatically
Note that enabling this setting will make you more vulnerable to viruses.
Once that is done, you need to decide where that macro should reside: in a worksheet, in the workbook, or as a VB module. The import method differs for each of these. I'm going to assume that it's in the workbook as it's the most common case. To add the content of that text file to the workbook macro:
excel = actxserver('Excel.Application');
workbook = excel.Workbooks.Open(full_path_to_your_file);
vbproject = workbook.VBProject; %Will error is trust access to the VBA project model is not enabled
workbookcomponent = vbproject.Components.Item('ThisWorkook');
workbookcomponent.CodeModule.AddFromFile(full_path_to_your_text_file);
workbook.SaveAs(full_path_as_xlsm_file, 52); %52 is xlOpenXMLWorkbookMacroEnabled
excel.Quit;