在Excel中从VBA调用带参数的MATLAB可执行文件

5uzkadbs  于 2023-01-09  发布在  Matlab
关注(0)|答案(1)|浏览(278)

我正在为一个程序设计一个前端。用户应该导入Excel工作表中的初始值,程序将Excel工作表连接到Matlab,运行Matlab代码并显示结果。因此,首先,Excel需要打开Matlab文件。我在VBA中使用以下代码找到Matlab路径并打开它:

Dim MatLab As Object

Set MatLab = CreateObject("Matlab.Application")

MatLab.Execute("C:\ProgramFiles\MATLAB\R2022b\toolbox\matlab\addon_enable_disable_management\matlab")

但此地址应针对所有用户进行推广,因为他们的MATLAB根不同。
**第二个问题是:**为了能够从Excel工作表中读取数据,我编写了一个MATLAB代码,它将读取工作表中的数字表,然后当我从Excel中的VBA代码调用这个Matlab文件时,它将运行程序并给予我一个三元图。但在这一节中,我还使用了MATLAB中Excel文件夹的特定地址,这需要推广。
我的Matlab代码是:

opts = spreadsheetImportOptions("NumVariables", 15);

opts.Sheet = "TernaryPlot1";

opts.DataRange = "A8:O20";

opts.VariableNames = ["Var1", "Var2", "Var3", "Var4", "Var5", "Var6", "Var7", "Var8", "Var9", "Var10", "Var11", "W4", "W5", "W6", "NormalizedResault"];

opts.SelectedVariableNames = ["W4", "W5", "W6", "NormalizedResault"];

opts.VariableTypes = ["char", "char", "char", "char", "char", "char", "char", "char", "char", "char", "char", "double", "double", "double", "double"];

opts = setvaropts(opts, ["Var1", "Var2", "Var3", "Var4", "Var5", "Var6", "Var7", "Var8", "Var9", "Var10", "Var11"], "WhitespaceRule", "preserve");

opts = setvaropts(opts, ["Var1", "Var2", "Var3", "Var4", "Var5", "Var6", "Var7", "Var8", "Var9", "Var10", "Var11"], "EmptyFieldRule", "auto");

opts = setvaropts(opts, ["W4", "W5", "W6", "NormalizedResault"], "FillValue", 0);

% Import the data

B = readtable("Path of my Excell folder ", opts, "UseExcel", false);

clear opts

% % Main file for ternary plot

A=table2array(B)

 warning off MATLAB:griddata:DuplicateDataPoints

l=length(A);

v=0.29./sqrt(A(:,4));

figure;

colormap(jet)
[hg,htick,hcb]=tersurf(A(:,1),A(:,2),A(:,3),A(:,4));

hlabels=terlabel('Weight on First goal','Weight on Second Goal','Weight on Third Goal');

citra3=montage(reshape(V,size(citra)),map,'Indices',3);

请帮助我找到我可以如何概括这两个地址(一个在VBA代码中关于我的MATLAB程序的地址,第二个在MATLAB程序中关于我的Excel文件夹的地址),以供每个用户在他们自己的计算机中使用。

pgvzfuti

pgvzfuti1#

我对VBA了解不多,所以欢迎讨论。基本上,当您调用

Set MatLab = CreateObject("Matlab.Application")
MatLab.Execute()

matlab executive的路径已经由系统通过OLE automation处理。您所需要做的就是将MATLAB函数与参数放在括号中。我使用内置的input function对一小段VBA代码进行了实验,作为概念验证。

Sub matlab()

Dim matlab As Object
Set matlab = CreateObject("Matlab.Application")
matlab.Execute ("input('put parameter here, e.g. enter to continue');")

End Sub

您可以在弹出窗口中观察结果。

相关问题