I have a for loop that opens and checks excel files, however it has been returning errors of such
Error using
Interface.Microsoft_Excel_14.0_Object_Library.Workbooks/Open
Invoke Error, Dispatch Exception:
Source: Microsoft Excel
Description: Excel cannot open the file
'interesting.xlsx' because the
file format or file extension is not valid. Verify that the file
has not been corrupted and that the file extension matches the
format of the file.
Help File: xlmain11.chm
Help Context ID: 0
So I try to locate the file and manually open it and it does returns me the same error of "Excel cannot open the file 'interesting.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
My goal here is not to fix the file, since I have a lot of files to read, some files may have problems, and I believe it is not a code problem, so I want to skip the problematic files and continue my loop.
Any suggestions? Thank you!

 채택된 답변

Stephen23
Stephen23 2016년 7월 15일
편집: Stephen23 2016년 7월 15일

1 개 추천

You can use try:
for k = ...
try
your code here
catch
fprintf('loop number %d failed\n',k)
end
end

댓글 수: 4

chlor thanks
chlor thanks 2016년 7월 15일
A few questions,
what specific code of mine should I paste under try?
what if I don't want any error message? Do I leave the line under catch blank?
Thanks Stephen! So glad to see you again :D
for example, can I do
for fileidx = 1:numel(filelist)
try
workbook = excel.Workbooks.Open(filelist{fileidx}, false, true);
catch
end
end
Like this..?
If you don't want to take any particular action and just ignore the error you can simply omit the catch part:
try
%some code that may error
end
%if an error occurs in the try block, execution continues from here
%... some more code
chlor thanks
chlor thanks 2016년 7월 15일
편집: chlor thanks 2016년 7월 18일
Wow, this is how it works! Thank you Guillaumeee

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2016년 7월 15일

편집:

2016년 7월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by