取消button应该退出子

我有一个代码来获得一个对话框来select一个文件夹的名称,并显示用户select的文件夹的名称。

但如果用户试图select取消而不是文件夹path和确定,则会引发错误。

根据我的观察我使用了一个状态variables,并注意到在取消状态更改为-1.so我试图实现在注释部分使用if条件退出子的代码。

但是,如果在代码中存在注释部分时select文件夹,这似乎不起作用。

没有它,它在select文件夹中工作正常。

有人可以请帮助吗?它的一分钟,我错过了什么:(

sub abc() Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker) diaFolder.AllowMultiSelect = False diaFolder.Title = "Select a folder then hit OK" diaFolder.Show 'Status = diaFolder.Show 'If Status < 0 Then 'Exit Sub 'End If a = diaFolder.SelectedItems(1) MsgBox ("Folder selected is :" & a) ens sub 

请记住,vbFalse = 0和vbTrue = -1。 换句话说,单击“确定”将返回-1,单击“取消”将返回0。

试试下面的代码:

 Sub abc() With Application.FileDialog(msoFileDialogFolderPicker) .AllowMultiSelect = False .Title = "Select a folder then hit OK" If .Show = -1 Then MsgBox ("Folder selected is :" & .SelectedItems(1)) Else Exit Sub End If End With End Sub 

如果没有select项目,* SelectedItems(1)*不存在,Excel将返回一个错误。 用户按下“ 取消”button时会发生这种情况。

一个解决scheme是检查使用下面的结构select了多less项目:

 With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = False 'Optional: limits the user to choosing a single option. Necessary if you want to avoid an error because the user selected multiple files. .Title = "Dialog Title" 'Changing the title is also Optional .Show If .SelectedItems.Count = 0 Then MsgBox "Canceled by user" 'or just do nothing! Else MyVar = .SelectedItems(1) End If 'Alternatively, "if .selecteditems.count = 1 then myvar = .selecteditems(1)" can be used End With