Vba 在Outlook中发送电子邮件时,如何自动运行宏?
下面的脚本工作得很好,但每次打开Outlook时,我都必须手动运行Initialize_handler例程Vba 在Outlook中发送电子邮件时,如何自动运行宏?,vba,outlook,Vba,Outlook,下面的脚本工作得很好,但每次打开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, Canc
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
就我所知,要使这项工作自动进行,我应该能够将下面的脚本添加到此OutlookSession。然而,这不起作用,我不知道为什么
我的宏安全性设置正确,它在启动时运行代码,但由于某些原因,在手动打开VBA编辑器并单击Initialize_处理程序并按F5之前,它无法工作
Private Sub Application_Startup()
Initialize_handler
End Sub
您可以直接将其放入此Outlook会话中:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
MsgBox "Sent somthing!"
End Sub
这里描述的卷积方法表示“样本代码必须放在类模块中” 我建议您仅在本次Outlook课程中使用特殊类模块。您可以使用自己的类模块进行实验,但如果您只是想让它工作,那么在这个OutlookSession中用它替换所有代码
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
就这么简单。注意:您需要将您的
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
。。。
...
...
outMail.Display(True)
出错时继续下一步
bSent=outMail.sent'这将不会发送。用于获取错误。
如果错误为0,则
“电子邮件已发送。把下面的动作放在这里。
其他的
'未发送电子邮件。把下面的动作放在这里。
如果结束
错误转到0
优点:
- 你得到你想要的
- 很简单
- Excel(或运行此代码的任何其他运行时)将冻结,直到您取消或发送电子邮件