Error 1004 when cancelling File dialog box in Excel VBA

Hi
I have some VBA code that opens a file.
The file itself is write-protected, so before it opens, a dialog box appears asking the user to either:
Enter the password and click OK button
Open as Read-Only
Cancel button (to cancel opening the file)

My problem is when the Cancel button is clicked, the VBA thows an error 1004 (error 1004 method open of object workbooks failed)
How can I handle / catch the case where a user clicks the Cancel button?
Thanks
Fergal
fjkilkenAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dustockCommented:
This worked for me.  If you don't want the MsgBox you could always 'Exit Sub' or anything else you want.

Private Sub ChooseFile()
   Set fd = Application.FileDialog(msoFileDialogFilePicker)
   With fd
        If .Show = True Then
            On Error GoTo ErrHandler:
            Workbooks.Open (fd.SelectedItems(1))            
        Else
            MsgBox "Dialog Cancelled"
        End If
   End With
   
ErrHandler:
   If Err.Number = 1004 Then
        MsgBox "Cancelled write protect screen"
    End If
End Sub

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
fjkilkenAuthor Commented:
Worked fine - thanks!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.