Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cancel button should exit the sub

Tags:

excel

vba

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

If the user selects cancel instead of folder path and OK, it throws an error.

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.

That doesn't work in the case of selecting a folder when the commented part is present in the code.

Without that it works in selecting a folder.

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
like image 917
user2075017 Avatar asked Dec 14 '22 18:12

user2075017


2 Answers

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
like image 176
Dustin Avatar answered Dec 26 '22 20:12

Dustin


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

like image 39
MrMyagi Avatar answered Dec 26 '22 20:12

MrMyagi