Exporting from Matlab to excel with macro.

19 views (last 30 days)
Matija Kosak
Matija Kosak on 10 Jul 2018
Commented: Matija Kosak on 10 Jul 2018
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.
Matija Kosak
Matija Kosak on 10 Jul 2018
Maybe you know way to do this? I'd appreciate it a lot.

Sign in to comment.

Accepted Answer

Guillaume on 10 Jul 2018
Edited: Guillaume on 10 Jul 2018
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');
workbook.SaveAs(full_path_as_xlsm_file, 52); %52 is xlOpenXMLWorkbookMacroEnabled
Matija Kosak
Matija Kosak on 10 Jul 2018
Can I maybe upload this empty file on internet, and than use it in matlab, and save it on computer? or that file should be on computer?

Sign in to comment.

More Answers (1)

Sayyed Ahmad
Sayyed Ahmad on 10 Jul 2018
you have to use activeX in matlab to start Excel
e = actxserver('excel.application');
%%new Woorkbook
eWorkbooks = get(e, 'Workbooks');
% neuWB=Add(eWorkbooks)
%%open a Workbook
Now you kann start your Macro in Excel
%%makro starten
e.ExecuteExcel4Macro(['!NameOfModule.NameOfSub(' INPUT_ValuesFromMatlabInExcel ')']);
%%save your work in excel
neuWB.Saved = 1;
%%excel clear and close
I hope that is what you need!
cheers Ahmad

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by