简体   繁体   中英

AddAttachment in excel VBA not able to attach file in outlook

I have written this very simple code to attach a file in my email, but the email comes without an attachment.

It doesn't even throw any error. I have made sure that the path is correct and the file exists. Please help

Private Sub CommandButton2_Click()
On Error GoTo ErrHandler

    ' SET Outlook APPLICATION OBJECT.
    Dim objOutlook As Object
    Set objOutlook = CreateObject("Outlook.Application")
    Dim Source_File As String

    ' CREATE EMAIL OBJECT.
    Dim objEmail As Object
    Set objEmail = objOutlook.CreateItem(olMailItem)

    With objEmail
        .To = "arushi.agarwal@in.ab-inbev.com"
        .Subject = "This is a test message k"
        .Body = "Please use this template for your weekly meeting today"
        .Send        ' SEND MESSAGE.
        .AddAttachment ("C:\Claims\Try.docx")
    End With

    ' CLEAR.
    Set objEmail = Nothing:    Set objOutlook = Nothing

ErrHandler:
    '

End Sub

I have made minor changes in your code and it works for me. You also need to attach the file before sending the email (eg .attachment before .send)

Private Sub CommandButton2_Click()
    On Error GoTo ErrHandler

    ' SET Outlook APPLICATION OBJECT.
    Dim objOutlook As Object
    Set objOutlook = CreateObject("Outlook.Application")
    Dim Source_File As String

    ' CREATE EMAIL OBJECT.
    Dim objEmail As Object
    Set objEmail = objOutlook.CreateItem(olMailItem)

    With objEmail
        .To = "arushi.agarwal@in.ab-inbev.com"
        .Subject = "This is a test message k"
        .Body = "Please use this template for your weekly meeting today"
        .Attachments.Add ("C:\Claims\Try.docx")
        .Send        ' SEND MESSAGE.
        '.AddAttachment ("C:\Claims\Try.docx")

    End With

    ' CLEAR.
    Set objEmail = Nothing:    Set objOutlook = Nothing
    Exit Sub
ErrHandler:
    Range("A1").Value = Err.Description
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM