Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

excel - Send only those emails that have attachments by way of a VBA code

I've just started working on macros and have made a pretty decent progress so far.

However, I'm stuck in a place and can't find an answer to it.

I'm using a macro to send emails to specific recipients via outlook. I'm sending multiple excel & pdf attachments in each email.

The code works fantastic! I, nonetheless, need to add a condition wherein an email that doesn't have any EXCEL attachments isn't sent and the outlook create mail item for this specific case only closes automatically.

The rest of the macro should continue for other clients with the excel attachments.

Hoping for someone to help me on this. Following is the code that I'm currently using.

Sub SendEmailWithReview_R()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim X As Long

    Lastrow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row

    For X = 10 To Lastrow
        Set OutApp = CreateObject("Outlook.Application")
        Set OutMail = OutApp.CreateItem(olmailitem)

        With OutMail
            .To = Cells(X, 4)
            .CC = Cells(X, 6)
            .Subject = Cells(X, 8)
            .Body = Cells(1, 8)

            strlocation = "C:UsersHKhanDesktopFinal Macro" & Cells(X, 1) & "-OICR.xlsx"
            On Error Resume Next
            .Attachments.Add (strlocation)
            On Error Resume Next
            strlocation = "C:UsersHKhanDesktopFinal Macro" & Cells(X, 1) & "-OICLR.xlsx"
            On Error Resume Next
            .Attachments.Add (strlocation)
            On Error Resume Next
            strlocation = "C:UsersHKhanDesktopFinal Macro" & "OIC - Bank Details" & ".pdf"
            On Error Resume Next
            .Attachments.Add (strlocation)
            On Error Resume Next
            strlocation = "C:UsersHKhanDesktopFinal Macro" & "OICL - Bank Details" & ".pdf"
            On Error Resume Next
            .Attachments.Add (strlocation)
            On Error Resume Next
            .Display
            'send
        End With  
    Next X
End Sub
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

So instead of waiting for errors or trying to suppress them better check if the file exists. Therefore you can use a function like this, which returns true if a file exists:

Public Function FileExists(FilePath As String) As Boolean
    Dim Path As String

    On Error Resume Next
    Path = Dir(FilePath)
    On Error GoTo 0

    If Path <> vbNullString Then FileExists = True
End Function

For adding attachments I recommend to use an array for the file names, so you can easily loop through and attach the files if they exist. Everytime we add an attachment we increase the AttachedFilesCount too.

This way you don't use On Error Resume Next wrong and you don't run into debug issues because of that. So you have a clean solution.

With OutMail
    .To = Cells(X, 4)
    .CC = Cells(X, 6)
    .Subject = Cells(X, 8)
    .Body = Cells(1, 8)

    Dim FileLocations As Variant
    FileLocations = Array("C:UsersHKhanDesktopFinal Macro" & Cells(X, 1) & "-OICR.xlsx", _
                          "C:UsersHKhanDesktopFinal Macro" & Cells(X, 1) & "-OICLR.xlsx", _
                          "C:UsersHKhanDesktopFinal Macro" & "OIC - Bank Details" & ".pdf", _
                          "C:UsersHKhanDesktopFinal Macro" & "OICL - Bank Details" & ".pdf")

    Dim AttachedFilesCount As Long

    Dim FileLocation As Variant
    For Each FileLocation In FileLocations
        If FileExists(FileLocation) Then
            .Attachments.Add (FileLocation)
            AttachedFilesCount = AttachedFilesCount + 1
        End If
    Next FileLocation

    If AttachedFilesCount > 0 Then
        .Display 'display or send email
    Else
        .Close 'close it if no attachments
    End If

End With

If you now still need additional error handling on adding the attachments (personally I don't think you need it necessarily) you can implement it like this:

On Error Resume Next  'turn error reporting off
.Attachments.Add (FileLocation) 'the line where an error might possibly occur.
If Err.Number <> 0 Then 'throw a msgbox if there is an error
    MsgBox "Could not attach file """ & FileLocation & """ to the email." & vbCrLf & Err.Description, vbExclamation, "Error " & Err.Number, Err.HelpFile, Err.HelpContext
End If
On Error Goto 0 'turn error reporting on again!

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...