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

8 ビュー (過去 30 日間)
Hidd_1
Hidd_1 2022 年 1 月 15 日
コメント済み: Walter Roberson 2022 年 1 月 15 日
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 Center および File ExchangeSpreadsheets についてさらに検索

製品


リリース

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by