Write to an already opened Excel file

71 vues (au cours des 30 derniers jours)
Diaa
Diaa le 10 Août 2020
The following MATLAB code works well for writing
eActiveSheetRange.Value
to the range
eActiveSheetRange
However, I have to keep the respective Excel file not opened by any application to make the writing process successful.
So, is there any way to keep the Excel file opened by, for example, Excel while making the MATLAB able to write to it without throwing errors and watch the new values be written?
excel = actxserver('Excel.Application');
wbooks = excel.Workbooks;
eWorkbook = wbooks.Open('C:\Users\Diaa\Desktop\test.xlsx');
eSheets = excel.ActiveWorkBook.Sheets;
sheet1 = eSheets.get('Item',1);
sheet1.Activate
eActiveSheetRange = get(excel.Activesheet,'Range','B1');
eActiveSheetRange.Value = 15;
eWorkbook.Save
excel.Quit
excel.delete
Edit 1
Following @J. Alex Lee's answer, I get this error
when running the following code while the file is opened by Excel at the same time:
FileName = 'C:\Users\Diaa\Desktop\test.xlsx';
SheetName = 'Sheet1';
SheetNum = find( sheetnames(FileName) == SheetName);
try
excel = actxserver('Excel.Application');
catch
excel = actxGetRunningServer('Excel.Application');
end
excel.Workbooks.Open(FileName).Sheets.Item(SheetNum).Activate
excel.Activesheet.Range('B1').Value = 88;
excel.Activeworkbook.Save
excel.Quit
excel.delete

Réponse acceptée

J. Alex Lee
J. Alex Lee le 11 Août 2020
If Excel is already running by the time you want to run this with the target file open, you can't just start a new excel instance and open that workbook; it will just create a new file with the same name, and when it comes time to save, you will get the error that the file is already open (anyway that's where I encountered error when I ran your example).
Instead, you need to fetch the open Excel instance
Excel = actxGetRunningServer('Excel.Application')
If you have multiple workbooks open in the excel instance, you'll need to find the one that you want within the list Workbooks.Item
Excel.Workbooks.Item(k).FullName
Such as by looping through and checking its FullName (full path, I think)
  4 commentaires
J. Alex Lee
J. Alex Lee le 11 Août 2020
So don't "Open" the workbook, if it already open in your excel app, you need to "point to it" using the Workbooks.Item property
Emmanuel J Rodriguez
Emmanuel J Rodriguez le 26 Avr 2022

Connectez-vous pour commenter.

Plus de réponses (0)

Produits


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by