Open file selection dialog, and get an error message when no file is selected

13 次查看(过去 30 天)
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.


Geoff Hayes
Geoff Hayes 2022-1-15
@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.');
filename = fullfile(filepath, file);
[num] = xlsread(filename);
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 个评论
Walter Roberson
Walter Roberson 2022-1-15
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
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.


更多回答(0 个)


Help CenterFile Exchange 中查找有关 Data Import from MATLAB 的更多信息




Community Treasure Hunt

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

Start Hunting!

Translated by