Hans
Hans

Reputation: 1379

How can I invoke an Excel Macro in Excel from Matlab?

I would like to invoke an Excel Macro or an VBA function in Excel from Matlab. How should achieve this? I suppose I should create a handle with

filename = './sampleWorkbook';
Excel = actxserver('Excel.Application');
workbook = Excel.Workbooks.Open(filename);

Then how should I proceed to invoke an VBA funciton in that Excel workbook filename?

Upvotes: 1

Views: 2298

Answers (2)

joehanna
joehanna

Reputation: 1489

You are almost there. Make a call to Application.Run("macroname") and you should be fine. Make sure macroname is in a VBA Module in your Excel Workbook and has Public scope.

filename = './sampleWorkbook';
Excel = actxserver('Excel.Application');
workbook = Excel.Workbooks.Open(filename);
Excel.Application.Run("macroname");

Here is a link to MSDN documentation for Application.Run : https://msdn.microsoft.com/en-us/library/office/ff197132.aspx

Upvotes: 3

Hans
Hans

Reputation: 1379

I have found the answer, coming very close to what joehanna has, but with the Run command in the correct Matlab format and closing the workbook previously opened and releasing the activeX server.

filename = 'C:\Book1.xlsm';
excel = actxserver('Excel.Application');
%excel.Visible = 1;
excel.Workbooks.Open(filename);
retval = excel.Run('trial');
excel.Workbooks(1).Close
excel.Quit
excel.release

Upvotes: 1

Related Questions