Matlab - Excel activex interface to pass data on opened instance

14 views (last 30 days)
Hi Community,
I have the following problem. I try to pass data from MATLAB Workspace to an opened Excel instance. Using the following script i manage to pass the data but i do not want to use in general the actxGetRunningServer, as the user can have other Excel instances opened.
Excel = actxGetRunningServer('Excel.Application');
ExcelWorkbook = Excel .Workbooks.Item(1);
ExcelSheet = ExcelWorkbook .ActiveSheet;
a = rand(5,1);
ExcelSheet.Range('A1:A5').Value = a;
ExcelWorkbook.Save
Excel.Quit
I tried then with:
% open the file
Excel = actxserver('Excel.Application');
try
ExcelWorkbook = Excel.workbooks.Open(fullfile(pwd, 'test.xlsx'));
catch ME
Excel.Quit
error('Failed.');
end
% Get the handle of the active Workbook
Sheets = get(get(Excel, 'ActiveWorkBook'), 'Sheets');
for iSheet = 1:Sheets.Count
SheetsName{iSheet,1} = Sheets.Item(iSheet).Name ;
end
[~,idx] = ismember('Cockpit',SheetsName);
Activate(Sheets.Item(idx));
a = rand(5,1);
Select(Range(Excel, 'A1:A5'));
set(Excel.selection, 'Value', num2cell(a));
ExcelWorkbook.Save
ExcelWorkbook.Close(false);
Excel.Quit
and in this case does not pass the data, instead ask to save another instance. I would appreciate a feedback. Thanks in advance!
  1 Comment
Greg
Greg on 19 Jan 2017
Your object access is completely inconsistent. It might be accurate, but it's extremely difficult to sort out what you're trying to do. You pull out a workbook handle, then you work on the activeworkbook.
My guess is change the last 3 lines to be:
Excel.ActiveWorkBook.Save;
Excel.ActiveWorkBook.Close(false);
Excel.Quit;

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!