Write to an already opened Excel file
77 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Diaa
am 10 Aug. 2020
Kommentiert: Emmanuel J Rodriguez
am 26 Apr. 2022
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
0 Kommentare
Akzeptierte Antwort
J. Alex Lee
am 11 Aug. 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 Kommentare
J. Alex Lee
am 11 Aug. 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
am 26 Apr. 2022
Here is another example where you can read/write to an open MS Excel file:
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu ActiveX finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!