使用VBA发送电子邮件之前检查附件

时间:2018-10-17 15:10:26

标签: vba count attachment

我有一个宏可以根据每列中的收件人起草自动电子邮件。

但是,我正在寻找一个代码,如果将excel表中命名的附件附加到电子邮件中,则可以。如果该电子邮件中缺少任何附件,它将显示一个msg框,其中包含丢失附件的名称。 SNip of one the sheets attached

Sub Email1()



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

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

Dim FLNM As String
Dim AttchmentName As String
Set AddressList = Sheets("Tracker Summary").Range("Y:Z")

Dim AttchmentName1 As String
Dim path As String

Call FetchFileNames

path = ThisWorkbook.path & "/"

Dim i As Integer

i = 5

With olMail

ActiveSheet.Range("A1").Select
.BodyFormat = olFormatHTML

    .Display
    .To = ActiveSheet.Cells(2, i).Value
    .CC = ActiveSheet.Cells(3, i).Value
    .Subject = ActiveSheet.Cells(4, i).Value
    .HTMLBody = ActiveSheet.Cells(5, i).Value & .HTMLBody
    j = 6

    Do Until IsEmpty(Cells(j, i))

    On Error Resume Next

    FLNM = ActiveSheet.Cells(j, i).Value

    AttchmentName1 = Application.WorksheetFunction.VLookup(FLNM, AddressList, 1, True)

    If FLNM = AttchmentName1 Then

    AttchmentName = Application.WorksheetFunction.VLookup(FLNM, AddressList, 2, True)

    .Attachments.Add AttchmentName

    End If

    j = j + 1

    Loop

    '.Display

    End With

Sheets("Tracker Summary").Range("Y:Z").ClearContents

End Sub

1 个答案:

答案 0 :(得分:0)

假设AttachmentName是完整的文件路径字符串,也许您的代码可以事先检查文件是否存在。

为简单起见...

If Len(Dir(AttachmentName)) = 0 then msgbox "The File " & AttachmentName & " is missing"

...在AttachmentName上设置AttchmentName = Application.WorksheetFunction.VLookup(FLNM, AddressList, 2, True)值之后

很明显,其他所有附件变量都一样。