0
votes

I have this code and it worked to get the attachment out of outlook and into the local folder. I have since tried to modify it to rename the file and delete the email from outlook and that is where it stopped working.

The rule moves the email when it comes in to a new folder, then saves the attachment to a folder on my C drive. Only 1 email per day and one attachment per day.

I would like to save the attachment to the folder, rename the attachment (overwriting the existing file), and delete the email from outlook.

This is the code I have so far.

Any help would be appreciated

Public Sub SaveAttachments(Item As Outlook.MailItem)

If Item.Attachments.Count > 0 Then

Dim objAttachments As Outlook.Attachments
Dim lngCount As Long
Dim strFile As String
Dim sFileType As String
Dim i As Long

Set objAttachments = Item.Attachments
lngCount = objAttachments.Count
For i = lngCount To 1 Step -1

' Get the file name.
strFile = objAttachments.Item(i).FileName

' Get the path to your My Documents folder
strfolderpath = "C:\Automation\CBM\"
'strfolderpath = strfolderpath & "\Attachments\"

' Combine with the path to the folder.
strFile = strfolderpath & strFile

' Save the attachment as a file.
objAttachments.Item(i).SaveAsFile FilePath & "Daily_Activity_Report" & 
".xlsx"

' Delete the attachment.
objAttachments.Item(i).Delete

Next i
End If

End Sub
1
What is FilePath?dwirony
The title "renaming and deleting attachment" does not match body "rename the file and delete the email". Which is correct?niton

1 Answers

0
votes

Try this:

Public Sub SaveAttachments(Item As Outlook.MailItem)

Dim objAttachments As Outlook.Attachments
Dim lngCount As Long
Dim i As Long

If Item.Attachments.Count > 0 Then

    Set objAttachments = Item.Attachments

    lngCount = objAttachments.Count

    For i = lngCount To 1 Step -1

        'Save the attachment as a file.
        objAttachments.Item(i).SaveAsFile "C:\Automation\CBM\Daily_Activity_Report.xlsx"

        'Delete the attachment.
        objAttachments.Item(i).Delete

    Next i

    Item.Save

End If

End Sub