Write to an already opened Excel file
82 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
J. Alex Lee
2020-8-11
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 个评论
J. Alex Lee
2020-8-11
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
2022-4-26
Here is another example where you can read/write to an open MS Excel file:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 ActiveX 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!