主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

将多个 MATLAB 函数分配给 Excel

MATLAB 中创建加载项

注意

为了使用 Microsoft® Excel® 函数语法 (=myfunction(input)) 调用 MATLAB® 函数,MATLAB 函数必须返回单个标量输出参量。要指定多个输出,请使用 Function Wizard 或自定义 VBA 代码创建宏。

  1. 将 MATLAB 附带的 xlbasic 文件夹复制到您的工作文件夹:

    copyfile(fullfile(matlabroot,'toolbox','matlabxl','examples','xlbasic'),'xlbasic')

    在 MATLAB 命令提示符下,导航到工作文件夹中的新 xlbasic 文件夹。

  2. 检查 MATLAB 函数 doubleit.mincrementit.mpowerit.m

     function output = doubleit(input)
       output = input * 2;
    function output = incrementit(input1, input2)
       output = input1 + input2;
     function output = powerit(input1, input2)
       output = power(input1, input2);
    
  3. 使用 Excel 加载项编译器compiler.build.excelAddIn 构建 Excel 加载项。

    将以下信息用于您的工程:

    加载项名称myexcelfunctions
    类名myexcelfunctionsclass
    要编译的文件

    doubleit.m
    incrementit.m
    powerit.m

    例如,如果您使用的是 compiler.build.excelAddIn,请输入:

    buildResults = compiler.build.excelAddIn(...
    ["doubleit.m","incrementit.m","powerit.m"],...
    "AddInName","myexcelfunctions",...
    "ClassName","myexcelfunctionsclass",...
    "GenerateVisualBasicFile","on",...
    "Verbose","on");

    有关详细信息,请参阅从 MATLAB 创建 Excel 加载项中的说明。

将加载项部署至 Microsoft Excel

  1. 若要将加载加载项给最终用户,请参阅分发加载项并集成到 Microsoft Excel 中

    注册组件并安装加载项后,您可以在电子表格中使用 doubleitincrementitpowerit 函数。

  2. 打开带有空白工作簿的 Microsoft Excel

  3. 通过执行以下操作来测试函数:

    1. 在单元格 A1 中输入 =doubleit(2.5)

    2. 在单元格 A2 中输入 =incrementit(11,17)

    3. 在单元格 A3 中输入 =powerit(7,2)

    您应该分别在单元格 A1A2A3 中看到值 52849

  4. (可选)通过将 doubleitpoweritincrementit 函数保存为模板,在新的 Microsoft Excel 电子表格中使用。

    1. 选择 File > Save As,然后选择文件类型 .xlt (Template)

    2. 浏览到 Office_Installation_folder\XLSTART 文件夹。

    3. 将文件另存为 Office_Installation_folder\XLSTART\Book.xlt

      注意

      您的 Microsoft Excel 宏安全级别必须设置为 MediumLow 才能保存此模板。