matlab/matlab-access-from-excel
Exchange data between Excel and MATLAB using Spreadsheet Link VBA macros and worksheet functions. Use when writing Excel VBA macros that call MLPutMatrix, MLGetMatrix, MLPutVar, MLGetVar, MLPutRanges, MLEvalString, MLGetFigure, or MatlabRequest.
npx skills add https://github.com/matlab/matlab-agentic-toolkit --skill matlab-access-from-excel
Spreadsheet Link connects Excel to MATLAB, enabling users to exchange data between Excel and MATLAB, run MATLAB commands, using MATLAB as the compute engine from Excel.
Spreadsheet Link uses VBA macros or worksheet functions in Excel to communicate with a locally running MATLAB instance via COM.
┌─────────────────────┐ VBA / COM ┌─────────────────────┐
│ Excel │ ◄─────────────────────► │ MATLAB │
│ (VBA or cells) │ │ (workspace) │
└─────────────────────┘ └─────────────────────┘
| Function | Mode | Purpose | Queued? |
|----------|------|---------|---------|
| MLPutMatrix | Both | Export worksheet range to MATLAB variable | No |
| MLPutVar | VBA only | Export VBA variable to MATLAB variable | No |
| MLGetMatrix | Both | Import MATLAB variable to worksheet cells | Yes |
| MLGetVar | VBA only | Import MATLAB variable into VBA variable | No |
| MLPutRanges | Both | Export ALL named ranges to MATLAB | No |
| MLEvalString | Both | Execute a MATLAB command | No |
| MLGetFigure | Both | Import current MATLAB figure as image | Yes |
| MatlabRequest | VBA only | Process all queued MLGetMatrix/MLGetFigure | — |
| MLAppendMatrix | Both | Append worksheet range to existing MATLAB variable | No |
Export an Excel range into MATLAB as a workspace variable.
VBA macro syntax:
MLPutMatrix "varName", Range("A1:B10")
Worksheet function syntax:
=MLPutMatrix("varName", A1:B10)
Export a VBA variable to the MATLAB workspace. VBA only — not available as a worksheet function.
Dim myData As Variant
myData = Range("A1:B100").Value
MLPutVar "matlabVar", myData
Queue a MATLAB variable to be written into Excel starting at a cell location.
MLGetMatrix "varName", "A1"
MatlabRequest is calleddatetime values are converted to strings in Excel=MLGetMatrix("varName", "E1")Import a MATLAB variable into a VBA variable. VBA only — not available as a worksheet function.
Dim result As Variant
MLGetVar "matlabVar", result
MatlabRequestdatetime values are converted to stringsExport ALL Excel named ranges to MATLAB in a single call. Each named range becomes a MATLAB variable with the same name.
MLPutRanges
prices)=MLPutRanges()Execute a MATLAB command in the connected MATLAB session.
MLEvalString "x = magic(3);"
=MLEvalString("x = magic(3);")Append an Excel range to an existing MATLAB variable. The new data is concatenated as additional rows.
VBA macro syntax:
MLAppendMatrix "varName", Range("A101:B200")
Worksheet function syntax:
=MLAppendMatrix("varName", A101:B200)
Import the current MATLAB figure into Excel as an image.
Range("I1").Select
MLGetFigure 1, 1
Range(...).SelectMatlabRequest is called (like MLGetMatrix)=MLGetFigure(1, 1) — places figure at the formula cellProcess all pending MLGetMatrix and MLGetFigure commands and write results to Excel.
MatlabRequest
MLGetMatrix or MLGetFigureMLGetVar (which executes immediately)Sub DataRoundTrip()
' Read data from worksheet into VBA variables
Dim prices As Variant
Dim weights As Variant
prices = Range("A1:A100").Value
weights = Range("B1:B100").Value
' Export VBA variables to MATLAB
MLPutVar "prices", prices
MLPutVar "weights", weights
' Compute in MATLAB
MLEvalString "portfolio = prices .* weights;"
MLEvalString "totalValue = sum(portfolio);"
' Import results into VBA variables (immediate — no MatlabRequest needed)
Dim portfolio As Variant
Dim totalValue As Variant
MLGetVar "portfolio", portfolio
MLGetVar "totalValue", totalValue
' Write VBA variables to worksheet
Range("D1").Resize(UBound(portfolio, 1), UBound(portfolio, 2)).Value = portfolio
Range("E1").Value = totalValue
End Sub
Sub ComputeInMatlab()
MLPutMatrix "data", Range("A1:C100")
MLEvalString "result = mean(data, 1);"
MLGetMatrix "result", "E1"
MatlabRequest
End Sub
Sub AnalyzeAllData()
' Export all named ranges to MATLAB at once
' e.g., "prices", "weights", "benchmark" all become MATLAB variables
MLPutRanges
' MATLAB code references variables by named range names
MLEvalString "portReturn = prices .* weights;"
MLEvalString "excessReturn = portReturn - benchmark;"
MLEvalString "sharpe = mean(excessReturn) / std(excessReturn) * sqrt(252);"
' Import result
Dim sharpe As Variant
MLGetVar "sharpe", sharpe
Range("H1").Value = sharpe
End Sub
Sub PlotAndImport()
MLPutVar "data", Range("A1:B100").Value
' Generate MATLAB figure
MLEvalString "figure;"
MLEvalString "plot(data(:,1), data(:,2), 'LineWidth', 1.5);"
MLEvalString "title('Analysis'); xlabel('X'); ylabel('Y'); grid on;"
' Import figure to Excel
Range("D1").Select
MLGetFigure 1, 1
MatlabRequest
End Sub
Sub MultipleFigures()
MLPutVar "data", Range("A1:C100").Value
' Create multiple figures
MLEvalString "figure(1); plot(data(:,1)); title('Series 1');"
MLEvalString "figure(2); histogram(data(:,2)); title('Distribution');"
MLEvalString "figure(3); scatter(data(:,1), data(:,2)); title('Scatter');"
' Import each — must make figure current before each MLGetFigure
MLEvalString "figure(1);"
Range("E1").Select
MLGetFigure 0.5, 0.5
MLEvalString "figure(2);"
Range("E20").Select
MLGetFigure 0.5, 0.5
MLEvalString "figure(3);"
Range("E40").Select
MLGetFigure 0.5, 0.5
MatlabRequest
End Sub
Sub TotalReturnWithFigure()
' Read data into VBA
Dim prices As Variant
Dim divs As Variant
prices = Range("A1:B253").Value
divs = Range("D1:E20").Value
' Export to MATLAB
MLPutVar "prices", prices
MLPutVar "divs", divs
' Compute total return
MLEvalString "dates = datetime(prices(:,1), 'ConvertFrom', 'excel');"
MLEvalString "px = prices(:,2);"
MLEvalString "exDates = datetime(divs(:,1), 'ConvertFrom', 'excel');"
MLEvalString "divAmounts = divs(:,2);"
MLEvalString "adjFactor = ones(size(px));"
MLEvalString "for i = 1:numel(exDates), idx = find(dates >= exDates(i), 1); if ~isempty(idx) && idx > 1, adjFactor(1:idx-1) = adjFactor(1:idx-1) * (1 - divAmounts(i)/px(idx)); end, end"
MLEvalString "totalReturn = px ./ adjFactor;"
MLEvalString "totalReturn = 100 * totalReturn / totalReturn(1);"
' Generate figure
MLEvalString "figure;"
MLEvalString "plot(dates, totalReturn, 'LineWidth', 1.5);"
MLEvalString "title('Total Return Index');"
MLEvalString "xlabel('Date'); ylabel('Index (Base = 100)'); grid on;"
' Import numeric result into VBA variable
Dim trResult As Variant
MLGetVar "totalReturn", trResult
Range("G1").Resize(UBound(trResult, 1), 1).Value = trResult
' Import figure
Range("I1").Select
MLGetFigure 1, 1
MatlabRequest
End Sub
Enter these in separate Excel cells, in order from top to bottom:
Cell F1: =MLPutRanges()
Cell F2: =MLEvalString("result = mean(prices, 1);")
Cell F3: =MLEvalString("figure; plot(prices); title('Prices'); grid on;")
Cell F4: =MLGetMatrix("result", "H1")
Cell F5: =MLGetFigure(1, 1)
Excel dates are sent as serial date numbers. Convert in MATLAB:
Dim rawData As Variant
rawData = Range("A1:B253").Value
MLPutVar "rawData", rawData
MLEvalString "dates = datetime(rawData(:,1), 'ConvertFrom', 'excel');"
MLEvalString "values = rawData(:,2);"
Two parallel APIs exist for exchanging data between Excel and MATLAB:
MatlabRequest is called. Available in both VBA and worksheet functions.| Scenario | Use |
|----------|-----|
| Data needs VBA manipulation before/after MATLAB | MLPutVar / MLGetVar |
| Direct range-to-MATLAB without VBA intermediary | MLPutMatrix |
| Result writes directly to cells without VBA processing | MLGetMatrix |
| Working within a larger VBA application | MLPutVar / MLGetVar |
| Simple cell formula workflow | MLPutMatrix / MLGetMatrix |
| Need result immediately (no MatlabRequest) | MLGetVar |
When generating VBA code that uses Spreadsheet Link:
.m files — Spreadsheet Link is an orchestration/data-exchange layer. Express MATLAB logic inline via MLEvalString calls. Calling pre-existing MATLAB functions or scripts is fine (e.g., MLEvalString "results = myAnalysis(data);"), but do NOT generate new .m files as part of the solution.MatlabRequest if the macro contains any MLGetMatrix or MLGetFigure calls. NOT needed if using only MLGetVar.MLGetMatrix takes a string for the cell address, not a Range object — use "G1" not Range("G1")MLGetFigure requires selecting the cell first — use Range("I1").Select then MLGetFigure 1, 1. Only two arguments (width, height scaling). Do NOT pass a cell address.MLPutMatrix takes a Range object for the data source — use Range("A1:B10")MLPutVar takes a VBA variable — use MLPutVar "name", myVar (not a string name of the variable)MLGetVar executes immediately — no MatlabRequest needed. Assign to a Variant.MLEvalString calls for multi-line MATLAB logic rather than packing into one string10. Convert dates after exporting — export raw data, then convert in MATLAB with datetime(..., 'ConvertFrom', 'excel')
11. Variable names must be valid MATLAB identifiers — no spaces, no special characters, must start with a letter
12. For multiple figures, make each figure current with figure(N) before each MLGetFigure call
13. Do NOT use exportgraphics + Shapes.AddPicture — use MLGetFigure instead
MLPutRanges exports ALL named ranges — it is not selectiveMatlabRequest during Excel recalculation — this is why worksheet functions do not need an explicit MatlabRequest call, while VBA macros doMLShowMatlabErrors "yes" — return MATLAB errors back to Excel (default is no; #COMMAND! is returned)MLOpen — verify or establish connection to MATLAB sessionMLClose — disconnect from MATLAB sessionMLAutoStart "yes" — auto-start MATLAB when the Spreadsheet Link add-in loadsMLUseFullDesktop "yes" — launch full MATLAB desktop vs Command Window onlyMLStartDir "C:\myproject" — set MATLAB working folder on connectionMLUseCellArray "yes" — toggle cell array mode for MLPutMatrix (sends each cell as a separate cell array element rather than combining into a matrix)MLProgramId "26.1" — set which MATLAB version to connect to when multiple versions are installedMLMissingDataAsNaN "yes" — send empty Excel cells as NaN to MATLAB (default sends as 0)----
Copyright 2026 The MathWorks, Inc.
Take matlab/matlab-access-from-excel from the repository into ~/.claude/skills for personal
use, or into .claude/skills inside a project.
The agent identifies a skill by the name field in its header. Two skills with the
same name cannot sit side by side — one of them will be ignored.