CommonDialog Cancel button handling in VB6

I am using Common Dialog to open the specified directory and give the user an ability to select the file and import it in.
But if I click the Cancel and don't select any file - it errorws out.  I need to know how to handle the Cacel button.
Who is Participating?
nffvrxqgrcfqvvcConnect With a Mentor Commented:
Forgot to attach the example by using cdlOFNFileMustExist flag it prevents the user from adding bogus information in this case the file must exists.
Private Sub Command1_Click()

Dim szFileName As String

CommonDialog1.CancelError = False
CommonDialog1.Flags = cdlOFNFileMustExist
szFileName = CommonDialog1.FileName

If LenB(szFileName) <> 0 Then
  Debug.Print szFileName
  Debug.Print "Cancel"
End If

CommonDialog1.FileName = vbNullString

End Sub

Open in new window

You can have it throw and error or you can just ignore cancel and check for a valid filename location.

If you add this line then an cdlCancel = 32755 (&H7FF3) will be thrown which you could trap.
CommonDialog1.CancelError = True

No error will be thrown
CommonDialog1.CancelError = False
There are two possible ways to handle this.

1. Before showing the window, you can set the common dialog property "CanelError" = False.  Then you will have to look at the contents of the return value to determine if the user cancled.

2. Add an error handler.  Catch Error #32755 to know the user clicked "Cancel"
  On Error Goto CatchError
  'Do stuff with selected File Here
  Exit Sub
  if Err.Number = 32755 then
    'Do stuff here based on the fact user clicked Cancel
    'Some other Error happened - handle it here

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.