vba 发送电子邮件时运行宏

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16044846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 20:37:40  来源:igfitidea点击:

Run macro when email is sent

vbaoutlookoutlook-vba

提问by Alex

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 MsgBoxwith 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.

但是我找不到任何听那个按钮的文档。现在,我只是想让它在发送MsgBox电子邮件时发送带有主题的邮件。有没有办法听(从 DOM 的角度思考)这个按钮并在点击时触发宏。

回答by Axel Kemper

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, "[email protected]"), _
              "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