MATLAB: If an error appears, how can I send the solution via message box to the user

errorexporting excel dataforcibly terminate excelkill excelMATLABxlswrite

Hi MATLAB-community, I have a program that reads an Excel-file via xlsread and after the program has finished it writes into the same sheet via xlswrite. My problem is: If the Excel-file is opened, MATLAB can't write because the file must be closed. And after the error message appears in the command window, I want to show a message box, that says: Please close the Excel-file! Like an if-structure: If 'error', then show msgbox. Thanks for your assistance!!

Best Answer

Try my attached function. To use:
try
% Some code that might throw an error...
catch ME
% Some error happened if you get here.
callStackString = GetCallStack(ME);
errorMessage = sprintf('Error in program %s.\nTraceback (most recent at top):\n%s\nError Message:\n%s',...
mfilename, callStackString, ME.message);
WarnUser(errorMessage)
end
Where WarnUser is basically
function WarnUser(errorMessage)
uiwait(errordlg(errorMessage));
fprintf('%s\n', errorMessage);
and GetCallStack is in the attached GetCallStack.m file.
To forcibly kill Excel, in Windows, use this code:
[taskstate, taskmsg] = system('tasklist|findstr "EXCEL.EXE"');
if ~isempty(taskmsg)
% Force shutdown of Excel.
status = system('taskkill /F /IM EXCEL.EXE');
end