问题
I have some VBA code in Excel that creates and sends an automatic email via Outlook. However the actual message is not getting sent unless I manually open up outlook to trigger the "send/receive". Below is the code that I use to create the email. I would think that all I need is one line of code to trigger the send/receive code. However I should point out that outlook isn't opening during this code. So one way to solve the problem might be to open outlook before this code, then close it after the code.
Function RDB_Mail_PDF_Outlook(FileNamePDF As String, StrTo As String, _
StrCC As String, StrBCC As String, StrSubject As String, _
Signature As Boolean, Send As Boolean, StrBody As String)
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
If Signature = True Then .Display
.To = StrTo
.CC = StrCC
.BCC = StrBCC
.Subject = StrSubject
.HTMLBody = StrBody & "<br>" & .HTMLBody
.Attachments.Add FileNamePDF
If Send = True Then
.Send
Else
.Display
End If
End With
On Error GoTo 0
SendReceiveAll = True
Set OutMail = Nothing
Set OutApp = Nothing
End Function
回答1:
This is to be expected -message submission is an asynchronous process, and Outlook closes before it has a chance to send the message.
Make OutApp variable global so it does not get released when your sub finishes, and call OutApp.Session.SendAndReceive
.
来源:https://stackoverflow.com/questions/45259485/email-created-using-vba-in-excel-not-sending