Calling and computing within Excel from Matlab
63 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Matt
le 4 Nov 2025 à 23:32
Modifié(e) : Walter Roberson
le 13 Nov 2025 à 17:34
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 commentaire
Cris LaPierre
le 5 Nov 2025 à 2:28
I'd suggest searching Answers for actx or activex.
Here's one post from MathWorks Support about communicating with Excel from MATLAB using ActiveX:
Réponse acceptée
Cris LaPierre
le 5 Nov 2025 à 2:41
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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Spreadsheets dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
