Search code examples
matlabcomchartsexcelvba

Insert a chart in excel sheet through Matlab


I am trying to insert a chart in a excel sheet. I am using the following code to insert the chart which is working.

Charts = Workbook.Charts;
Chart = invoke(Charts,'Add');

try
    Excel.ActiveChart.Name = chart_title;
catch e
    errordlg(e.message);
    invoke(Excel,'Quit');        
    error(['Sheet (' chart_title ') already exists!']);        
end

However, this will create a new sheet for the chart with data from all the columns. But, I would like to create a chart ( does not matter if it is a new sheet) but only with a selected column, say something like B2:B16 ( use only selected column)

Any idea, how to do it ?

Thanks


Solution

  • It's relatively simple. I was able to get all the information I needed from the Microsoft Office Excel document page.

    Here's all the commands I used.

    % Open up the active server and get a workbook
    Excel = actxserver('Excel.Application');
    Workbook = Excel.workbooks.Open('d:\Temp\test.xlsx');
    % Add a chart to the workbook
    Chart = invoke(Workbook.Charts,'Add');
    % Specify the range for the chart
    invoke(Chart, 'SetSourceData', Excel.Range('Sheet1!$B$2:$B$16'));
    % Make excel visible
    Excel.Visible = true;