-1

I am trying to build a Matlab script to write data to an Excel file, have the excel file execute, and pull out another cell as the output. I asked an AI engine to give me a script and it came up with this. It looks like it could work, but it doesn't. Any advice? I'd like to put this in a large for loop to call the excel function multiple times.

% Import the Excel add-in
% Make sure to have the 'ActiveX' control enabled in your Matlab environment
% If not, you can use 'xlswrite' and 'xlsread' functions instead

% Create an Excel object
excel = actxserver('Excel.Application');

% Set visibility to false (optional)
excel.Visible = 'False';

% Open an existing workbook or create a new one
workbook = excel.Workbooks.Open('C:\path\to\your\file.xlsx');
% workbook = excel.Workbooks.Add;

% Get the first worksheet
sheet = workbook.Worksheets(1);

% Write data to a cell
sheet.Cells(1, 1).Value = 'Hello, World!';

% Save the workbook
workbook.Save;

% Force calculation
excel.Calculate;

% Read a cell value
cell_value = sheet.Cells(1, 1).Value;

% Display the cell value
disp(cell_value);

% Clean up
sheet = [];
workbook = [];
excel.Quit;
excel = [];
1
  • Thanks for the comment @Jefferson Francisco. 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. Here is a simple task that will likely get me what I need. 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? Commented Nov 4 at 23:23

1 Answer 1

4

It’s close, but there are a few issues in your code. Mainly, excel.Visible should be a logical value (not a string), and you should properly close and clean up the COM object. Also, calling excel.Calculate alone doesn’t always recalc the sheet — you should call sheet.Calculate instead.

Here’s a working version:

excel = actxserver('Excel.Application');
excel.Visible = false;

workbook = excel.Workbooks.Open('C:\path\to\your\file.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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.