Search code examples
vbaformsms-accessoutlookvba6

Error Catch if DoCmd.SendObject is terminated prematurely


I have a email (SendObject) routine in MSAccess VBA. The code crashes if the user decides not to commit to hit the send button, and simply closes the email form.

Private Sub ButtonSupportEmail_Click()

Dim varName As Variant
Dim varCC As Variant
Dim varSubject As Variant
Dim varBody As Variant

varName = "[email protected]"
varCC = "[email protected]"

varSubject = "ADB Front End Client Support_" & Now()
varBody = "Dear Amazing ADB Support Team:"
DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False

End Sub

Is there an error catch I can add that prompts (via a popup form) the user "No email sent" and closes gracefully?

Fig A: Error from user closing Outlook Email Form
enter image description here


Solution

  • Add error handling and ignore the 2501 - Operation cancelled error.

    Private Sub ButtonSupportEmail_Click()
        On Error GoTo Trap
    
        Dim varName As Variant
        Dim varCC As Variant
        Dim varSubject As Variant
        Dim varBody As Variant
    
        varName = "[email protected]"
        varCC = "[email protected]"
    
        varSubject = "ADB Front End Client Support_" & Now()
        varBody = "Dear Amazing ADB Support Team:"
        DoCmd.SendObject , , , varName, varCC, , varSubject, varBody, True, False
    
    Leave:
        Exit Sub
    
    Trap:
        If Err.Number <> 2501 Then MsgBox Err.Description, vbCritical
        Resume Leave
    End Sub