发送电子邮件时运行宏

时间:2013-04-16 18:53:34

标签: vba outlook outlook-vba

我正在尝试编写一个宏,当用户点击“发送”按钮时,该宏会查看电子邮件的主题行。

但是,我无法找到任何听取该按钮的文档。现在,我只是想让它在发送电子邮件时发送MsgBox主题。有没有办法倾听(根据DOM 思考)到这个按钮并在点击时激活一个宏。

1 个答案:

答案 0 :(得分:4)

正如Siddharth所说:

我写了一个小的演示,它检查一些条件来决定是否应该取消发送操作。这可以扩展到做其他事情,比如插入日期,将邮件保存到某个文件夹,......

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