取消按钮应退出该子

时间:2014-11-22 12:54:35

标签: excel vba

我有一个对话框来选择文件夹名称并显示用户选择的文件夹的名称。

如果用户选择取消而不是文件夹路径并且确定,则会引发错误。

我使用了一个状态变量,并注意到取消后状态变为-1。因此,我尝试使用if条件实现注释部分中的代码以退出子。

在代码中存在注释部分时选择文件夹时不起作用。

没有它,它可以用于选择文件夹。

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

3 个答案:

答案 0 :(得分:8)

请记住,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

答案 1 :(得分:1)

Sub abc()
 Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
    diaFolder.AllowMultiSelect = False
    diaFolder.Title = "Select a folder then hit OK"
    Dim status As Integer
    status = diaFolder.Show
    If status <> -1 Then
    MsgBox "Cancel Chosen"
    Exit Sub
    End If
    a = diaFolder.SelectedItems(1)
    MsgBox ("Folder selected is :" & a)
End Sub

我知道此功能已被关闭,但想尝试首次发布。 = D

答案 2 :(得分:0)

如果没有选择项目,* SelectedItems(1)*不存在,Excel将返回错误。当用户按下取消按钮时,就会发生这种情况。

解决方法是使用以下结构检查选择的项目数:

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
相关问题