仅为某些 outlook 宏触发 ItemSend

Trigger ItemSend for certain outlook macros only

如何修改下面的代码来触发事件myMailItem_ItemSend只在myMacro1发送邮件时触发,而在其他情况下(例如myMacro2)不触发?

应该触发该事件,尤其是那些使用 myMailItem 对象的宏。

Public WithEvents myMailItem As Outlook.MailItem

Public Sub Initialize_handler() 
    Set myMailItem = Outlook.MailItem
End Sub 

Private Sub myMailItem_ItemSend(ByVal Item As Object, Cancel As Boolean) 
    Dim prompt As String 
    prompt = "Are you sure you want to send " & Item.Subject & "?" 
    If MsgBox(prompt, vbYesNo + vbQuestion, "Send confirmation") = vbNo Then 
        Cancel = True 
    End If 
End Sub

'Should trigger the send confirmation msgbox
Private Sub myMacro1()
    Dim objApp As Outlook.Application
    Set objApp = Application
    Set myMailItem = objApp.ActiveInspector.CurrentItem.ReplyAll
    myMailItem.Display
End Sub

'Should NOT trigger the send confirmation msgbox
Private Sub myMacro2()
    Dim objApp As Outlook.Application
    Set objApp = Application
    Dim oEmail As Outlook.mailItem
    Set oEmail = objApp.ActiveInspector.CurrentItem.ReplyAll
    oEmail.Display
End Sub

我们将不胜感激。

我会这样做:

  1. 在你的模块中定义一个全局变量,例如Dim TriggerMsgBox As Boolean。默认情况下,该变量将为 false。
  2. myMacro1()中将其初始化为True。只有那样,它才会变成True。否则,它将是 False.
  3. myMailItem_ItemSend事件中使用:如果变量是True(意思是我们刚刚通过myMacro1()),那么你需要提示MsgBox。否则,你只会擦肩而过。当然,不要忘记在点击 MsgBox 后将变量重置为 False,否则你会在以后继续显示它。

在您的代码中它将是:

Public WithEvents myMailItem As Outlook.MailItem
Dim TriggerMsgBox As Boolean '<-- NEW LINE OF CODE

Public Sub Initialize_handler() 
    Set myMailItem = Outlook.MailItem
End Sub 

Private Sub myMailItem_ItemSend(ByVal Item As Object, Cancel As Boolean) 
    Dim prompt As String 
    If TriggerMsgBox Then '<-- NEW LINE OF CODE
        TriggerMsgBox = False '<-- NEW LINE OF CODE
        prompt = "Are you sure you want to send " & Item.Subject & "?" 
        If MsgBox(prompt, vbYesNo + vbQuestion, "Send confirmation") = vbNo Then 
            Cancel = True 
        End If
    End If '<-- NEW LINE OF CODE
End Sub

'Should trigger the send confirmation msgbox
Private Sub myMacro1()
    Dim objApp As Outlook.Application
    Set objApp = Application
    Set myMailItem = objApp.ActiveInspector.CurrentItem.ReplyAll
    TriggerMsgBox = True '<-- NEW LINE OF CODE
    myMailItem.Display
End Sub

'Should NOT trigger the send confirmation msgbox
Private Sub myMacro2()
    Dim objApp As Outlook.Application
    Set objApp = Application
    Dim oEmail As Outlook.mailItem
    Set oEmail = objApp.ActiveInspector.CurrentItem.ReplyAll
    oEmail.Display
End Sub