VBA将附加PDF并通过Outlook发送电子邮件

时间:2019-03-25 19:20:00

标签: vba

我是VBA的新手。我正在编写一个VBA代码,该代码将从excel的通讯组列表中发送电子邮件。我也希望它附加一个PDF文件。我大部分内容都是书面的,但是我不知道该写什么来附加PDF(硬盘上只有一个PDF)。 A列是电子邮件地址,C列是名称,E列具有PDF的路径,而单元格J2包含电子邮件正文。如果我想将pdf附在E列的路径中,有人可以告诉我我的代码应该怎么说?我只有4行正在测试,但是我希望它只发送所有内容,直到最后一行,这可能会有所不同。实际上是两个宏,如果只有1:

我将不胜感激任何帮助。谢谢。

Sub SendEmail(what_address As String, subject_line As String, mail_body As String)

Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")

Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)

olMail.To = what_address
olMail.Subject = subject_line
olMail.Body = mail_body
olMail.Send

End Sub
Sub SendMassEmail()

row_number = 1

Do
DoEvents
    row_number = row_number + 1
    Dim mail_body_message As String
    Dim full_name As String
    mail_body_message = Sheet2.Range("J2")
    full_name = Sheet2.Range("c" & row_number)
    mail_body_message = Replace(mail_body_message, "replace_name_here", full_name)
    Call SendEmail(Sheet2.Range("A" & row_number), "Request for Tax Exemption Certificate", mail_body_message)
Loop Until row_number = 4


End Sub

1 个答案:

答案 0 :(得分:0)

假定代码中的所有其他内容均按预期工作。然后,您需要在olMail.Send方法之前添加以下行。示例:

olMail.attachments.Add Sheets("Sheet1").Range("E2").Value, olByValue, , "sampleFile"

有关attachments.add方法的更多信息,请点击此处Attachments Add

发送邮件功能如下:

Sub SendEmail(what_address As String, subject_line As String, mail_body As String)

Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")

Dim olMail As Outlook.MailItem
Set olMail = olApp.CreateItem(olMailItem)

olMail.To = what_address
olMail.Subject = subject_line
olMail.Body = mail_body
olMail.attachments.Add Sheets("Sheet1").Range("E2").Value, olByValue, , "sampleFile"
olMail.Send

End Sub

编辑1:我想您的问题是如何在电子邮件中包含多个附件。然后您可以尝试以下方法:

Sub SendEmail(what_address As String, subject_line As String, mail_body As String)

Dim olApp As Outlook.Application
Set olApp = CreateObject("Outlook.Application")
Dim olMail As Outlook.MailItem
Dim lastRow As Integer

Set olMail = olApp.CreateItem(olMailItem)

'Provide the Column where the attachment links are stored. I guess its E in your case
lastRow = Sheets("Sheet1").Range("E" & Rows.Count).End(xlUp).Row

olMail.To = what_address
olMail.Subject = subject_line
olMail.Body = mail_body

'Loop through the column and add the attachments to the Email
For i = 2 To lastRow
    .attachments.Add Sheets("Sheet1").Range("E" & i).Value, olByValue
Next i
olMail.Send

End Sub