How do I skip an error in a loop?

89 views (last 30 days)
chlor thanks
chlor thanks on 15 Jul 2016
Edited: chlor thanks on 18 Jul 2016
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!

Accepted Answer

Stephen
Stephen on 15 Jul 2016
Edited: Stephen on 15 Jul 2016
You can use try:
for k = ...
try
your code here
catch
fprintf('loop number %d failed\n',k)
end
end
  4 Comments
chlor thanks
chlor thanks on 15 Jul 2016
Wow, this is how it works! Thank you Guillaumeee

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by