How to automatically run a macro on opening a draft in Outlook? (add a BCC)

大城市里の小女人 提交于 2019-12-11 00:15:52

问题


I'm trying to automatically achieve this workflow:

  • when user opens a message draft in Outlook (a generated EML file)
  • if the subject matches a string (immutable, known beforehand, I can't change it; it's something like xyžřy, note the non-ASCII characters):
  • then add an e-mail to BCC field (immutable, known beforehand, valid e-mail address; let's say it's baz@example.com)

I already know the last part - how to add a BCC to a message, and I use InStr for matching:

Sub addbcc()
Dim objRecip As Recipient
Set oMsg = Application.ActiveInspector.CurrentItem

With oMsg

     If InStr(1, oMsg.Subject, "xyžřy") > 0 Then

        Set objRecip = oMsg.Recipients.Add("baz@example.com")
        objRecip.Type = olBCC
        objRecip.Resolve

    End If

End With

Set oMsg = Nothing

End Sub

However, the user still needs to remember to press a button to run this macro, which is not more convenient than typing the BCC manually. Is it possible to run the macro automatically when this e-mail is opened?


回答1:


Is it possible to run the macro automatically when this e-mail is opened?

Work with NewInspector Event , Events occurs when new window is opened by user or through your code.

Example

Option Explicit
Private WithEvents Inspectors As Outlook.Inspectors

Private Sub Application_Startup()
    Initialize_handler
End Sub

Public Sub Initialize_handler()
    Set Inspectors = Application.Inspectors
End Sub

Private Sub Inspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
    If Inspector.currentItem.Class = olMail Then
        If Inspector.currentItem.Parent = "Drafts" Then ' Drafts Folder

            Debug.Print Inspector.currentItem.Subject ' Immediate Window
            ' Call Your Code
            ' Inspector.currentItem.BCC = "baz@example.com"
        End If
    End If
End Sub

CurrentItem Property




回答2:


You could monitor the drafts folder with ItemAdd. See the idea here for the inbox. How do I trigger a macro to run after a new mail is received in Outlook?

You could add the bcc in ItemSend. Outlook 2010 - VBA - Set bcc in ItemSend



来源:https://stackoverflow.com/questions/37592269/how-to-automatically-run-a-macro-on-opening-a-draft-in-outlook-add-a-bcc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!