Open file selection dialog, and get an error message when no file is selected
8 views (last 30 days)
Show older comments
Hey Everybody!
I wrote the following code, for a GUI app:
[file,filepath,filter] = uigetfile({'*.xlsx'},'Select the Excel file');
filename = fullfile(filepath, file);
[num] = xlsread(filename);
and I would like that the user get an error message when he/she doesn't select a file.
0 Comments
Accepted Answer
Geoff Hayes
on 15 Jan 2022
@Hidd_1 - on my version of MATLAB (2021a), if I don't select a file, then the parameters file and filepath are 0. You could add something like the following to your code to catch this case
[file,filepath,filter] = uigetfile({'*.xlsx'},'Select the Excel file');
if isnumeric(file) || isnumeric(filepath)
errordlg('You have not selected a file.');
else
filename = fullfile(filepath, file);
[num] = xlsread(filename);
end
At one time, I thought that if you didn't select a file then these parameters would be empty. That might no longer be the case, but if it is true for your version of MATLAB, just replace isnumeric with isempty.
1 Comment
Walter Roberson
on 15 Jan 2022
When multiselect is off, then when the user selects a file without cancel, ischar(file) is true, and is false if the user cancels.
When multiselect is on, then file could also be cell so ischar(file)||iscell(file) but also consider
if ischar(file); file = {file}; end
if ~iscell(file);
%user canceled
end
This is useful because when multiselect is on but the user selects exactly one file, then char is returned, but if the user selects multiple files then cell is returned.
More Answers (0)
See Also
Categories
Find more on Spreadsheets in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!