Calling and computing within Excel from Matlab
조회 수: 13 (최근 30일)
이전 댓글 표시
Let's say I have an excel worksheet where A1 = 3; A2 = 4; and A3 = A1+A2. I want to feed a new value of A1 and A2 in from Matlab of values 5 and 6. I then want Excel to make the calculations and then I want to pull out the A3 value which will be 11. How can I make code to do that?
I've tried to ask AI for some help and it has produced the following code.
excel = actxserver('Excel.Application');
excel.Visible = false;
workbook = excel.Workbooks.Open('C:\Book1.xlsx');
sheet = workbook.Worksheets.Item(1);
sheet.Cells(1, 1).Value = 'Hello, World!';
workbook.Save;
sheet.Calculate;
value = sheet.Cells(1, 1).Value;
disp(value);
workbook.Close(false);
excel.Quit;
delete(excel);
You would think that code would put in the value "Hello World" in the first cell in the worksheet and then save after calculating. Turns out, it puts "Hello World" in every cell within the worksheet.
댓글 수: 1
Cris LaPierre
2025년 11월 5일
I'd suggest searching Answers for actx or activex.
Here's one post from MathWorks Support about communicating with Excel from MATLAB using ActiveX:
채택된 답변
Cris LaPierre
2025년 11월 5일
Something like this works for me
% Specify file name
path = cd;
name = "Book1.xlsx";
file = fullfile(path,name); % This must be full path name
% Open Excel Automation server
Excel = actxserver('Excel.Application');
Workbooks = Excel.Workbooks.Open(file);
excelWB_sheet_1=Workbooks.Sheets.Item(1); %Get first sheet
% Change values of cells A1 and A2
excelWB_sheet_1.Range('A1').Value = 5;
excelWB_sheet_1.Range('A2').Value = 10;
Excel.Calculate; % Force Excel to compute equations
% Extract value from cell A3 and save to a MATLAB variable
valueA3 = excelWB_sheet_1.Range('A3').Value
% Close the workbook and quit Excel application
Workbooks.Close(false); % false to not save changes
Excel.Quit;
delete(Excel); % Release the COM server
댓글 수: 8
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Spreadsheets에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
