Why do I receive a "Run-time error '13': Type mismatch" error when I try to access the data returned by MLGETVAR?

12 views (last 30 days)
I am using the MLGETVAR command in my Excel Visual Basic for Applications (VBA) macro to get a variable from the MATLAB workspace into Excel. I have created a slightly modified version of the simple example in the Spreadsheet Link EX documentation; the VBA code is as follows:
Sub Fetch()
MLGetVar "J", DataJ
MsgBox (DataJ)
End Sub
That is, I have inserted a call to MsgBox to verify the data I am receiving from MATLAB. In the MATLAB workspace, the variable J is a scalar.
When running the above VBA code, I get a dialog box with the error message: ERROR: Run-time error '13': Type mismatch

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 19 Dec 2019
Edited: MathWorks Support Team on 18 Dec 2019
This change has been incorporated into the documentation in Release 2009a (R2009a). For previous releases, read below for any additional information:
The type mismatch error is due to the type of the variable (DataJ) that is used to hold the value returned by MLGETVAR command. The variable that is created by MATLAB to hold the value when MLGETVAR returns is of type Variant() - that is, it is an array of Variants.
Since the returned variable DataJ is an array, it must be indexed in order to use the values it contains. Thus, the call to MsgBox should be coded as follows if the variable J in the MATLAB workspace is a scalar:
MsgBox(DataJ(1,1))
This will cause the VBA code to run without error.
Likewise, if J is a matrix of dimension MxN in the MATLAB workspace, you can index into the corresponding (m,n)-th element in DataJ with the following statement:
MsgBox(DataJ(m,n))
All other VBA array conventions apply.
A similar example of indexing into a Variant() variable as returned by MLGETVAR can be found in the following Spreadsheet Link EX example in the documentation:
If you have installed the help documentation, you may access the same page locally by typing the following at the MATLAB prompt:
web([docroot,'/toolbox/exlink/f2-2311.html#brfcgkq'])

More Answers (0)

Categories

Find more on Data Export to MATLAB in Help Center and File Exchange

Tags

Products


Release

R2008a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!