Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vba - Run macro when email is sent

I am trying to write a macro that looks at the subject line of an email whenever the user hits the Send button.

However I can't find any documentation that listens to that button. For right now I am just trying to get it to send a MsgBox with the subject when the email is sent. Is there a way to listen (thinking in terms of DOMs) to this button and fire a macro on the click.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As suggested by Siddharth:

I have written a small demo which checks some conditions to decide, if the send operation should be canceled. This could be extended to do other things like inserting dates, saving the mails to some folder, ...

Option Explicit

Private Sub Application_ItemSend(ByVal objItem As Object, Cancel As Boolean)
    Dim mi As MailItem

    If TypeName(objItem) = "MailItem" Then
        Set mi = objItem

        Debug.Print mi.Subject

        check Cancel, Trim(mi.Subject) <> "", "Subject is empty!"
        check Cancel, Not isRecipient(mi, "John@Doe.net"), _
              "John is on our embargo list!"
    End If
End Sub

Private Sub check(ByRef Cancel As Boolean, cond As Boolean, msg As String)
    If Not (Cancel Or cond) Then
        Cancel = (MsgBox(msg & vbCrLf & "Cancel send operation?", _
                         vbYesNoCancel, "Confirm?") <> vbNo)
    End If
End Sub

Private Function isRecipient(mi As MailItem, forbidden As String) As Boolean
    Dim ret As Boolean
    Dim rc As Recipient

    ret = False

    For Each rc In mi.recipients
        If StrComp(rc.Address, forbidden, vbTextCompare) = 0 Then
            ret = True
            Exit For
        End If
    Next

    isRecipient = ret
End Function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...