noway
noway

Reputation: 2585

Closing Send Mail Window after Canceling Item Send event within Outlook via VBA

I'm coding a VBA Macro to prevent sending emails to a specified email address. It's an Outlook Macro which runs under the ThisOutlookSession. Code runs fine, but the problem is that I can't close the Send Mail window.

I added a line (marked in the code) which throws an error that "The Item.Close command cannot be performed during Item.Send event"

It's understandble, but how can I overcome this?

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

 If Item.To = "[email protected]" Then
     Prompt$ = "Are you sure you want to send this message?"
   If MsgBox(Prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check before Sending") = vbNo Then
    Cancel = True

    Item.Close olDiscard          ' <<< ERROR HERE 

  End If
End If

End Sub

Upvotes: 0

Views: 2527

Answers (2)

DragonSamu
DragonSamu

Reputation: 1163

Instead of closing the Item itself which can't be done when the send event is still running you close the Item Inspector.

See below:

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim objInsp As Inspector
Dim Strmsg As String
Set objInsp = Item.GetInspector
If Item.To = "[email protected]" Then
    Strmsg = "Are you sure you want to send this message?"
    If MsgBox(Strmsg, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check before Sending") = vbNo Then
        Cancel = True
        objInsp.Close 1
    End If
End If
End Sub

Upvotes: 3

Dmitry Streblechenko
Dmitry Streblechenko

Reputation: 66235

In languages other than VBA, you can use a timer - enable the timer in the ItemSend event, when the timer event fires (you will be out of the ItemSend event handler by then), disable the time and close the inspector.

I don't think you can use a timer in Outlook VBA though...

Upvotes: 0

Related Questions