Closed smartini87 closed 1 year ago
The collection now returns "nothing" when user cancels the operation. Otherwise the users gets an error because the function wouldn't return a Collection as expected.
Hi @smartini87 ,
The current method returns an Collection
with zero items if the user cancels.
The line If .Show = actionButton Then
specifically checks if the user cancelled and the If
statement is only entered if the user did not cancel. However, because the Set BrowseForFiles = New Collection
line is immediately before the If
statement, then the function never returns Nothing
. Instead it will always return an instantiated collection with either zero items (user cancelled) or one/multiple files based on the allowMultiFiles
parameter.
I had the option to choose of these 2 options:
1) to return Nothing
if the user cancelled, which is what you are proposing
2) to return a zero-item collection if the user cancelled, which is what I went for
At first glance, you might wonder why I did not return Nothing
because it's the obvious choice. Well, since this is a general-purpose library, I wanted something that minimizes the risk of runtime errors and I wanted to give more flexibility to the potential user.
Consider the following snippet:
With BrowseForFiles(initialPath:=previousPath _
, dialogTitle:="Choose Test File" _
, filterDesc:="Excel Files" _
, filterList:="*.xlsx;*.xlsm;*.xlsb" _
, allowMultiFiles:=False)
If .Count = 0 Then Exit Function
path_ = .Item(1)
End With
With your change, the above would become:
Dim coll As Collection
Set coll = BrowseForFiles(initialPath:=previousPath _
, dialogTitle:="Choose Test File" _
, filterDesc:="Excel Files" _
, filterList:="*.xlsx;*.xlsm;*.xlsb" _
, allowMultiFiles:=False)
If coll Is Nothing Then Exit Function
path_ = coll.Item(1)
As you can see we cannot use a With
construct because within the construct we cannot check for Nothing
. It would be nice if the Collection
class had a method like .Self
or .Me
or .This
but unfortunately it does not.
So, I will keep the current form of the method. Thank you for your feedback!
Added cancel handler in case the user cancels the operation while selecting file(s) in Sub "BrowseForFiles".