我需要您的帮助才能完成此任务!我对VBA一无所知,但是浏览互联网时,我创建了一个带有宏的excel文件,用于将电子邮件发送到每个电子邮件都有不同附件的不同地址。
现在,邮寄可以正常工作,但前提是所有文件都存在。文件地址是自动定义的,每个月我都会发送各种电子邮件,并附带2或3个文件,但是有几个月文件地址没有文件,因此VBA不会生成电子邮件。
我需要的是,即使文件不存在,也要使用现有文件创建电子邮件并移至下一封电子邮件。
代码是这样:
Sub send_email_with_multiple_attachments()
On Error Resume Next
Dim o As Outlook.Application
Set o = New Outlook.Application
Dim omail As Outlook.MailItem
Dim i As Long
For i = 2 To Range("c100").End(xlUp).Row
Set omail = o.CreateItem(olMailltem)
With omail
.Body = "Caro cliente " & Cells(i, 2).Value
.To = Cells(i, 3).Value
.CC = Cells(i, 4).Value
.Subject = Cells(i, 5).Value
.Attachments.Add Cells(i, 6).Value
.Attachments.Add Cells(i, 7).Value
.Attachments.Add Cells(i, 8).Value
.Attachments.Add Cells(i, 9).Value
.Attachments.Add Cells(i, 10).Value
.Display
End With
Next
End Sub
您需要先检查单元格的内容,然后再将其添加为附件。查看下面的代码,并查看代码注释:
Option Explicit
Sub send_email_with_multiple_attachments()
' section of all objects and parameters declaration
Dim o As Outlook.Application
Dim omail As Outlook.MailItem
Dim strFileExists As String
Dim i As Long, j As Long
Set o = New Outlook.Application
For i = 2 To Range("c100").End(xlUp).Row
Set omail = o.CreateItem(olMailItem)
With omail
.Body = "Caro cliente " & Cells(i, 2).Value
.To = Cells(i, 3).Value
.CC = Cells(i, 4).Value
.Subject = Cells(i, 5).Value
' add second loop to check all cells with possible attachments
For j = 6 To 10
' make sure cells is not empty
If (Cells(i, j).Value) <> "" Then
strFileExists = Dir(Cells(i, j).Value) ' make sure file exits in current cell
If strFileExists <> "" Then ' only if file exits add as attachment
.Attachments.Add Cells(i, j).Value
End If
End If
Next j
.Display
End With
Next
End Sub