Write to an already opened Excel file

조회 수: 69 (최근 30일)
Diaa
Diaa 2020년 8월 10일
댓글: Emmanuel J Rodriguez 2022년 4월 26일
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

채택된 답변

J. Alex Lee
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
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
Emmanuel J Rodriguez 2022년 4월 26일

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 ActiveX에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by