Main Content

Assign Multiple MATLAB Functions to Excel Class

Create Add-In In MATLAB

Note

In order to call a MATLAB® function using the Microsoft® Excel® function syntax (=myfunction(input)), the MATLAB function must return a single scalar output argument. To specify multiple outputs, create a macro using the Function Wizard or custom VBA code.

  1. Copy the xlbasic folder that ships with MATLAB to your work folder:

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

    At the MATLAB command prompt, navigate to the new xlbasic folder in your work folder.

  2. Examine the MATLAB functions doubleit.m, incrementit.m, and powerit.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. Build the Excel add-in with the Library Compiler app or compiler.build.excelAddIn.

    Use the following information for your project:

    Add-in Namemyexcelfunctions
    Class Namemyexcelfunctionsclass
    Files to Compile

    doubleit.m
    incrementit.m
    powerit.m

    For example, if you are using compiler.build.excelAddIn, type:

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

    For more details, see the instructions in Create Excel Add-In from MATLAB.

Deploy Add-In to Microsoft Excel

  1. To deploy your add-in to end users, see Distribute Add-Ins and Integrate into Microsoft Excel.

    After you register the component and install the add-in, you can use the doubleit, incrementit, and powerit functions in your spreadsheet.

  2. Open Microsoft Excel with a blank workbook.

  3. Test the functions by doing the following:

    1. Enter =doubleit(2.5) in cell A1.

    2. Enter =incrementit(11,17) in cell A2.

    3. Enter =powerit(7,2) in cell A3.

    You should see the values 5, 28, and 49 in cells A1, A2, and A3, respectively.

  4. (Optional) Use the doubleit, powerit, and incrementit functions in new Microsoft Excel spreadsheets by saving it as a template.

    1. Select File > Save As and select the file type .xlt (Template).

    2. Browse to the Office_Installation_folder\XLSTART folder.

    3. Save the file as Office_Installation_folder\XLSTART\Book.xlt.

      Note

      Your Microsoft Excel Macro Security level must be set at Medium or Low to save this template.