Main Content


Write contents of MATLAB matrix in Microsoft Excel VBA variable



MLGetVar ML_var_name, VBA_var_name writes the contents of MATLAB® matrix ML_var_name in the Excel® Visual Basic® for Applications (VBA) variable VBA_var_name. The MLGetVar function creates VBA_var_name if it does not exist. The function replaces existing data in VBA_var_name.


collapse all

Define a matrix variable in MATLAB and write its contents into a VBA variable using a VBA macro.

Define a 4-by-3 matrix A in MATLAB. The A variable appears in the MATLAB Workspace.

A = [1,2,3;4,5,6;7,8,9;10,11,12]
A =

     1     2     3
     4     5     6
     7     8     9
    10    11    12

On the Developer tab in Excel, click Visual Basic in the Code group. The Visual Basic Editor window opens.

From the Insert menu, select Module to insert a new module. In the Module1 window, enter this VBA code containing a macro named GetVar. Write the contents of the MATLAB matrix A into the VBA variable data.

Sub GetVar()
    MLGetVar "A", data
End Sub

The GetVar macro uses the MLGetVar function to access the contents of variable A from the MATLAB Workspace. Then, the function writes the contents of the variable to the VBA variable data. For details about working with modules, see Excel Help.

Run the macro by clicking the Run Sub/UserForm button on the VBA toolbar. For details about running macros, see Excel Help.

The MLGetVar function accesses the contents of the variable and writes them to the VBA variable.

Input Arguments

collapse all

Name of the MATLAB matrix to access, specified as a string. ML_var_name in quotes directly specifies the matrix name. ML_var_name without quotes specifies a VBA variable that contains the matrix name as a string.

Do not use the MATLAB variable ans as ML_var_name. If defined, ML_var_name must be specified with the VARIANT type. With any other type, the MLGetVar function returns a "TYPE MISMATCH" error.

Example: "A"

Name of the VBA variable where the function writes the contents of ML_var_name, specified as a string. Use VBA_var_name without quotes.

Example: data


  • To work with VBA code in Excel with Spreadsheet Link™, you must enable Spreadsheet Link as a reference in the Microsoft® Visual Basic Editor. For details, see Installation.

Version History

Introduced before R2006a