Cancel button should exit the sub

2019-02-20 12:02发布

问题:

I have got a code to get a dialog box to pick a folder name and display the name of the folder that the user selects.

But in case if the user tries to select cancel instead of folder path and OK,then it throws an error.

As per my observations i used a status variable and noticed that upon cancel the status changes to -1.so i tried to implement the code that is in comment section using a if condition to exit the sub.

But that doesn't seem to work in case of selecting a folder when the commented part is present in the code.

Without that it works fine in selecting a folder.

Could someone please help in this?Its a minute step,i am missing out something :(

  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

回答1:

Keep in mind that vbFalse = 0 and vbTrue = -1. In other words clicking 'OK' would return -1 and clicking 'Cancel' would return 0.

Try the following code:

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


回答2:

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

I know this is closed out but wanted to try posting for the first time. =D



回答3:

If there are no items selected, *SelectedItems(1)*doesn't exist, and Excel will return an error. That's what's happening when the user presses the Cancel button.

A solution for this is to check how many items are selected using the structure below:

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