Can Matlab write a macro in an Excel file via ActiveX?

There are a few posts and instructions on how to run Excel macros using Matlab through ActiveX. But is it possible to write such a macro using Matlab into an Excel file?

Background: I wrote a Matlab tool that exports data to Excel files. These Excel files must contain a specific macro, which depends on the data contained.

Well there is an ugly workaround: I can create Excel templates with a specific macro already included. Then the corresponding template is copied and filled with export data. But perhaps there is a better and more flexible solution to this problem ...

+4
source share
1 answer

, VBA, (*.txt *.bas), , , VBA, :

DataFileName = 'D:\Test\DataFile.xlsm';
CodeFileName = 'D:\Test\CodeFile.txt';

Excel = actxserver('Excel.Application');
Workbooks = Excel.Workbooks;
Workbook=Workbooks.Open(DataFileName);

% Make Excel visible (Optional)
Excel.visible = 1;

%% Import the code
Import(Workbook.VBProject.VBComponents,CodeFileName);

%% Save
Excel.Application.DisplayAlerts = 0; %Avoid overwrite warning
SaveAs(Workbook,DataFileName);
Excel.Application.DisplayAlerts = 1;

%% Close Excel
Quit(Excel);
delete(Excel);

CodeFile.txt :

Attribute VB_Name = "ModuleName"
Option Explicit

Sub SomeMacro()

    Msgbox "From MATLAB, with love..."

End Sub

Attribute VB_Name = ... . Option Explicit , .

+1

Source: https://habr.com/ru/post/1691984/


All Articles