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
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:
I know this is closed out but wanted to try posting for the first time. =D
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: