如何在Outlook中发送电子邮件时自动运行宏?

时间:2016-03-04 21:27:14

标签: vba outlook-vba

下面的脚本效果很好但每次打开Outlook时我都必须手动运行Initialize_handler例程。

Public WithEvents myOlApp As Outlook.Application

Public Sub Initialize_handler()
Set myOlApp = CreateObject("Outlook.Application")
End Sub

Private Sub myOlApp_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, "Sample") = vbNo Then
    Cancel = True
    End If
End Sub

据我所知,我可以自动将此工作添加到ThisOutlookSession中。然而,这不起作用,我不知道为什么。

我的宏安全设置正确并且它在启动时运行代码但由于某种原因它直到我手动打开VBA编辑器点击进入Initialize_handler并按F5才能工作。

Private Sub Application_Startup()
  Initialize_handler
End Sub

3 个答案:

答案 0 :(得分:3)

此处描述的复杂方法https://msdn.microsoft.com/en-us/library/office/ff865076.aspx表示“示例代码必须放在类模块中”。

我建议你只使用特殊的类模块ThisOutlookSession。您可以尝试使用自己的类模块,但如果您只是希望这样做,那么在ThisOutlookSession中将所有代码替换为。

Private Sub Application_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, "Sample") = vbNo Then
    Cancel = True
    End If
End Sub

答案 1 :(得分:1)

您可以直接将其放在ThisOutlookSession

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    MsgBox "Sent somthing!"
End Sub

答案 2 :(得分:1)

就这么简单。请注意,您需要将outMail.Display更改为outMail.Display (True),并且完整代码:

...
...
...
outMail.Display (True)

On Error Resume Next
bSent = outMail.sent 'This will NOT SEND. Used to get error.
If Err <> 0 Then
    'Email was sent. Put followed actions here.
Else
    'Email was not sent. Put followed actions here.
End If
On Error GoTo 0

优点:

  • 你得到你想要的东西
  • 很简单。

缺点:

  • Excel(或您运行此代码的任何其他运行时)将冻结,直到您取消或发送电子邮件。