Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 在Outlook中发送电子邮件时,如何自动运行宏?_Vba_Outlook - Fatal编程技术网

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

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

下面的脚本工作得很好,但每次打开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
就我所知,要使这项工作自动进行,我应该能够将下面的脚本添加到此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(或运行此代码的任何其他运行时)将冻结,直到您取消或发送电子邮件

这不起作用。事实上,即使手动执行,代码本身也不会做任何事情。@niton指出,如果不传入参数,则无法手动调用此函数。即使手动运行,此代码本身也不会做任何事情。如果不传入参数,则无法运行需要参数Item的代码。但这不是主要问题。测试前是否重新启动了Outlook?是的,但这并不重要,因为这段代码不应该以任何方式执行任何操作。如果您将所有代码替换为此,则不会调用它。本网站上有许多示例将此作为ItemSend的标准用法进行演示,只剩下检查你的安全设置了。谢谢你的帮助。我一定是在什么地方被一段代码搞乱了。我得到了反馈,删除了我所有的东西,包括一些其他模块,现在它确实像你说的那样工作了。我不知道我哪里出错了,但非常感谢你的帮助。