Save Attachments from Outlook using VBA
You can use the following code to save attachments from outlook using VBA.
Note: Either create a folder called attachments on your C: drive or create a folder somewhere else to hold the attached files and then edit the path in the code.
Option Explicit
Sub SaveAtts()
Dim ns As NameSpace
Dim fld2SaveAtt As MAPIFolder
Dim MailItem As Object
Dim Att As Attachment
Dim FileName As String
Dim intFiles As Integer
On Error GoTo HandleError
Set ns = GetNamespace("MAPI")
Set fld2SaveAtt = ns.GetDefaultFolder(olFolderInbox)
intFiles = 0
If fld2SaveAtt.Items.Count = 0 Then
MsgBox "There were no messages found in your Inbox."
Exit Sub 'there are no messages, so Exit the Sub
End If
'Loop through Mail Items
For Each MailItem In fld2SaveAtt.Items
'Loop through any attachments
For Each Att In MailItem.Attachments
FileName = "C:Attachments" & Trim(Att.FileName)
Att.SaveAsFile FileName
intFiles = intFiles + 1
Next
Next
' Show summary message
If intFiles > 0 Then
MsgBox intFiles & " attachments were saved to " ^ _
"C:Attachments."
Else
MsgBox "No attachments were found"
End If
Set Att = Nothing
Set MailItem = Nothing
Set ns = Nothing
Exit Sub
HandleError:
MsgBox "Error: " & Err.Number & vbCrLf & _
"Description: " & Err.Description & vbCrLf & _
"The file's name is " & FileName
intFiles = intFiles - 1
Resume Next 'Continue saving attachments
End Sub
Return from Save Attachments from Outlook using VBA to "VBA Code Samples"
Return to our "Home page"

|