VBA Outlook Mail .display,如果手动发送则录制

时间:2016-06-22 08:50:10

标签: excel vba excel-vba email outlook

我使用VBA从Excel发送电子邮件,并且很难尝试记录邮件是否已发送。我从这里的另一篇文章中获取了一些代码:

Link

我完全按照描述创建了类,并添加了一些额外的位来查看它是否正常工作,它初始化,但是没有其他事情发生 - 即使在发送邮件之后,类仍然在后台以某种方式打开,所以我必须在VBE中停止它。

这是调用代码:

Sub SendProc2(add As String)

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)

On Error Resume Next

With OutMail
    .To = add
    .CC = ""
    .BCC = ""
    .Subject = ThisWorkbook.Name
    .Body = Application.WorksheetFunction.VLookup(Worksheets("Data").Range("B135"), Range("formversion"), 2, False) _
    & " Attached:" & vbCrLf & vbCrLf & ThisWorkbook.Name
    .Attachments.add ActiveWorkbook.FullName
    .Display   'or use .Send
End With

Dim CurrWatcher As EmailWatcher
Set CurrWatcher = New EmailWatcher
Set CurrWatcher.TheMail = OutMail

On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing

Unload UserForm4

End Sub

这里是类模块代码,名为EmailWatcher:

Option Explicit
Public WithEvents TheMail As Outlook.MailItem

Private Sub Class_Terminate()

Debug.Print "Terminate " & Now()

End Sub

Private Sub TheMail_Send(Cancel As Boolean)

Debug.Print "Send " & Now()
'enter code here

End Sub

Private Sub Class_Initialize()

Debug.Print "Initialize " & Now()

End Sub

似乎永远不会注册_Send,我认为这可能与未被定义的类对象或其他东西有关,我已经遇到了很多麻烦,有时我会收到警告,目前它是正在初始化,然后立即终止而不等待_Send,帮助将不胜感激,如果需要更多信息,请告诉我。

在Windows 7上使用Excel 2007,通过一个我无法控制的疯狂的本地授权网络。

我对VBA也不陌生,但我以前从未上过课,做了很多标准模块等。

谢谢,

2 个答案:

答案 0 :(得分:0)

Private WithEvents EM As Outlook.MailItem

Public Sub INIT(x As Outlook.MailItem)
    Set EM = x
End Sub

Private Sub EM_Send(Cancel As Boolean)

End Sub

模块

Public WATCHER As clsEmailWatch

Sub EMAIL()

Dim o As Outlook.Application
Dim m As Outlook.MailItem

Set o = New Outlook.Application
Set m = o.CreateItem(olMailItem)

Set WATCHER = New clsEmailWatch
WATCHER.INIT m

m.To = "xyz@abc.com"

m.Send

End Sub

希望这有帮助

答案 1 :(得分:0)

这似乎与在运行用户窗体时显示邮件有关。

我遇到的一个问题是,尽管存在用户窗体,但Outlook事件没有注册。为了解决这个问题,我实施了一种技巧:

您的类或用户窗体模块中需要一个布尔属性:

Private someBool as Boolean

您需要订阅MailItem.Close Event并设置新的布尔值:

Private Sub TheMail_Close(Cancel As Boolean)
    someBool = True
End Sub

关闭,发送或保存显示的电子邮件时,引发此事件。

那么您显然需要一个Property Get方法:

Public Property Get MailClosed() As Boolean
    MailClosed = someBool
End Property

现在,要处理所有事件,您需要在模块中显示一个来自以下位置的邮件的循环:

[...]
Dim CurrWatcher As EmailWatcher
Set CurrWatcher = New EmailWatcher
Set CurrWatcher.TheMail = OutMail

Do Until CurrWatcher.MailClosed
    DoEvents
Loop

[...]

我不确定DoEvents为何有效,如果有人可以对它有所了解,我会将其添加到我的答案中。