How do you detect whether the user pressed cancel when using common dialog boxes?
Alex
Printable View
How do you detect whether the user pressed cancel when using common dialog boxes?
Alex
It's a property of the common dialog called 'Cancel Error'.
When this is set to true, an error is generated (32755 to be exact) and your program can execute code based on this error or you can set it to false and have your program do absolutely nothing.
You should use the On Error Statement and With statement.
Code:Private Sub ..._...()
On Error Goto User_Cancelled
With CommonDialog1
'do whatever
End With
Exit Sub
User_Cancelled:
Msgbox "User cancelled!", 16
End Sub
Thanks people, just seems strange that you have to check for an error rather than there being a way to check the cancel property of the common dialogue box e.g something like
if (commonDialog1.cancel=true) then exit sub
Thanks,
Alex
You do have to set it to true.
Missing from Matthew's code.
Code:Private Sub Form_Load()
'display the commondialog show open
On Error GoTo errhandle:
CommonDialog1.InitDir = "C:\" 'set dir path
CommonDialog1.CancelError = True 'used in cancel code
CommonDialog1.Filter = "All files(*.*)|*.*" 'filter for all files
CommonDialog1.ShowOpen 'show files
'Extracts Filename only
MsgBox Mid(CommonDialog1.FileName, InStrRev(CommonDialog1.FileName, "\") + 1)
'Extracts File Path only
MsgBox Left(CommonDialog1.FileName, InStrRev(CommonDialog1.FileName, "\") - 1)
Exit Sub
errhandle:
End Sub