
Wherever possible you should try to anticipate an error which might arise in the context of the procedure or function being executed. In the error handler you can then specifically address that error and take appropriate action. In the following procedure for instance the code attempts to create a folder. If the folder already exists an error with an Err.Number of 75 will be raised. This can be ascertained by firstly executing the code without any error handling and seeing what Err,Number is returned. The number is then assigned to a constant FOLDER_EXISTS in the code to make the code more readable, and the error handling inserted to detect that error.
In this case, if the error indicates that the folder exists the line Resume Next in the error handler causes the code to continue executing at the line following that which raised the error, as there is no need to create a new folder for the remaining code to execute successfully.
It's possible that some unanticipated error might occur for reasons which you have not foreseen. In this case the error handler will return the Err.Description in a message box. The Description property might give you a clear idea of what has caused the error, or it might return a cryptic message which tells you very little or nothing useful. That is as much as you can expect unfortunately.
Private Sub cmdPDF_Click()
On Error GoTo Err_Handler
Const FOLDER_EXISTS = 75
Const MESSAGE_TEXT1 = "No current invoice."
Const MESSAGE_TEXT2 = "No folder set for storing PDF files."
Dim strFullPath As String
Dim varFolder As Variant
If Not IsNull(Me.InvoiceNumber) Then
' build path to save PDF file
varFolder = DLookup("Folderpath", "pdfFolder")
If IsNull(varFolder) Then
MsgBox MESSAGE_TEXT2, vbExclamation, "Invalid Operation"
Else
' create folder if does not exist
varFolder = varFolder & "\" & Me.Customer.Column(1)
MkDir varFolder
strFullPath = varFolder & "\" & Me.Customer.Column(1) & " " & Me.InvoiceNumber & ".pdf"
' ensure current record is saved before creating PDF file
Me.Dirty = False
DoCmd.OutputTo acOutputReport, "rptInvoice", acFormatPDF, strFullPath, True
End If
Else
MsgBox MESSAGE_TEXT1, vbExclamation, "Invalid Operation"
End If
Exit_Here:
Exit Sub
Err_Handler:
Select Case Err.Number
Case FOLDER_EXISTS
Resume Next
Case Else
MsgBox Err.Description
Resume Exit_Here
End Select
End Sub