Why does reading some Excel data via ACTXSERVER return an error if I open another Excel file outside of MATLAB?

2 views (last 30 days)
I have a large Excel file full of numerical data that I am trying to read in the following way:
hExcel = actxserver('excel.application');
hExcel.Workbooks.Open('test.xlsx');
data = hExcel.Worksheets.Item('Sheet1').UsedRange.Value;
hExcel.Quit;
delete(hExcel)
The data is read correctly when I run the code. However, I obtain the following error if I open an Excel file outside of MATLAB while the code is running:
Error using Interface.000208D7_0000_0000_C000_000000000046/Item
Invoke Error, Dispatch Exception: Invalid index.
Error in example_actxserver_read (line 4)
data = hExcel.Worksheets.Item('Sheet1').UsedRange.Value;

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 12 Sep 2013
This error occurs because the 'UsedRange' method reads data from the currently active worksheet on the Excel process, which is also the last opened Excel file.
In order to work around this issue, you should read the data using the file handle returned by the Open method instead of the handle returned by ACTXSERVER as demonstrated in the following example:
hExcel = actxserver('excel.application');
excelFileHandle = hExcel.Workbooks.Open('test.xlsx');
data = excelFileHandle.Worksheets.Item('Sheet1').UsedRange.Value;
excelFileHandle.Close;
hExcel.Quit;
delete(hExcel)
Please note that there is only one Excel process, even if you double click the file in a file explorer. Therefore, both Excel files will be closed by running hExcel.Quit as this kills the Excel process.

More Answers (0)

Tags

No tags entered yet.

Products


Release

R2013a

Community Treasure Hunt

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

Start Hunting!