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

조회 수: 8 (최근 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.');
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
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
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.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by