VBA Excel File Open Prompt Cancel Error

grimchamp picture grimchamp · Apr 9, 2013 · Viewed 20.8k times · Source

So I am using a file open prompt to gather a filename. I then open this file in a background instance, parse information to a dictionary and close the file. This works fine. The code for this is:

Application.FileDialog(msoFileDialogOpen).Show
sFullName = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

If the user presses cancel, which is obviously a feasible scenario, I get the following error:

Invalid procedure call or argument

I have tried to change the 'gather' line to:

If Application.FileDialog(msoFileDialogOpen).SelectedItems(1) Then sFullName = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)

However this still brings up the error. Even disabling alerts brings up an error or '400'. Any help on how to make this popup or handle it would be greatly appreciated.

Answer

Alex K. picture Alex K. · Apr 9, 2013

You need check the bounds to determine if anything was selected

with Application.FileDialog(msoFileDialogOpen)

    .Show

    if (.SelectedItems.Count = 0) Then
        '// dialog dismissed with no selection
    else
        sFullName = .SelectedItems(1)
    end if
end with