MATLAB: How to create a small macro in Excel that gets data from MATLAB via ActiveX

activexexcelmacroMATLAB

I am trying to create a small macro in Excel that gets data from MATLAB via ActiveX but I am unable to do so. Would it be possible to provide an example?

Best Answer

In order to create a small macro in Excel that gets called from MATLAB via ActiveX control, please follow the steps mentioned below:
1. Start Excel.
2. Go to the Tools menu of Excel and select Macro-->Macros. A dialog box will appear.
3. Enter Example1 in the Macro Name box, and click on Create. A Visual Basic editor will appear.
You are now ready to enter your macro. The following is an example of a macro that produces a mesh grid in MATLAB and returns the peaks matrix. The first and last lines of the macro should already appear in the sheet Module1.
'===============================================
' Example1 Macro
' Macro recorded 02/21/95 by The MathWorks, Inc.
'===============================================
' Declare a Matlab variable here so it stays open
' when Sub Example1 goes out of scope
Dim MatLab As Object
Sub Example1()
'Create the Matlab Object
Set MatLab = CreateObject("Matlab.Application")
'Execute MATLAB commands
Result = MatLab.Execute("h=peaks(10);colormap(pink);mesh(h);drawnow")
'Get some matrix from MATLAB
Dim MReal(9, 9) As Double
Dim MImag() As Double
Dim RealValue As Double
Dim i, j As Integer
'Result = MatLab.Execute("a = [1 2 3 4; 5 6 7 8;]")
Call MatLab.GetFullMatrix("h", "base", MReal, MImag)
'Make sheet1 active. This selects the target sheet.
'Commenting out this line means that the sheet
'operated on is the current sheet.
Sheets("sheet1").Select
'Put in a string
Range("B10:B10").Value = "The content of variable h"
'Fill Excel sheet cells with data from MATLAB
Range("B11:K20").Value = MReal
End Sub
Once this macro is complete, save it and close out of the Visual Basic Editor. You can run the macro by opening the macros dialog box in Excel, selecting Example1, and clicking on Run.
You can also download an example macro that has already been set up by clicking on the file below.