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

做~自己de王妃 提交于 2019-12-10 15:56:35

问题


There are several posts and instructions how to run Excel macros with Matlab via ActiveX. But is it possible to write such a macro with Matlab into an Excel file?

Background: I wrote a Matlab tool which exports data into Excel files. These Excel files should have a specific macro included which is dependend on the containing data.

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


回答1:


Once you have allowed programmatical access to the VBA Project, I would suggest to write your macro to a text file (*.txt or *.bas) and then run the command that would import this text file has a VBA code module. For example:

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);

In this case, CodeFile.txt could look like this:

Attribute VB_Name = "ModuleName"
Option Explicit

Sub SomeMacro()

    Msgbox "From MATLAB, with love..."

End Sub

Here, the line Attribute VB_Name = ... is essential and will determine the name of the module. For Option Explicit, it is not mandatory, but it's good practice.



来源:https://stackoverflow.com/questions/48190180/can-matlab-write-a-macro-in-an-excel-file-via-activex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!