Processing multiple emails


August 25, 2008 – 1:23 pm by JP

    In Highlight And Move Multiple Emails, I demonstrated a technique for processing several emails at once and moving them to another folder. Here is another example that shows how you can save attachments from several selected emails, then delete them.

VBA:
  1. Sub SaveEmailAttachments()
  2.  
  3. Dim Msg As Outlook.MailItem
  4. Dim MsgColl As Object
  5. Dim MsgAttach As Outlook.Attachments
  6. Dim i As Long
  7. Dim FileN As String
  8. Dim lAttach As Long
  9.  
  10. On Error Resume Next
  11. Set MsgColl = ActiveExplorer.Selection
  12. On Error GoTo 0
  13.  
  14. If Not MsgColl Is Nothing Then
  15.   For i = 1 To MsgColl.Count
  16.    
  17.     ' loop through selected items and save all attachments from each of them
  18.     Set Msg = MsgColl.Item(i)
  19.     Set MsgAttach = Msg.Attachments
  20.    
  21.     For lAttach = 1 To MsgAttach.Count
  22.       FileN = MsgAttach.Item(lAttach).DisplayName
  23.       MsgAttach.Item(lAttach).SaveAsFile "C:\My Folder\" & FileN
  24.     Next lAttach
  25.  
  26.   Next i
  27.    
  28.     If MsgBox("Would you like to delete the selected emails now?", _
  29.      vbInformation + vbYesNo) = vbYes Then
  30.         For i = 1 To MsgColl.Count
  31.           Set Msg = MsgColl.Item(i)
  32.           Msg.Delete
  33.         Next i
  34.     End If
  35. Else
  36.   GoTo ExitProc
  37. End If
  38.  
  39. ExitProc:
  40. Set MsgAttach = Nothing
  41. Set Msg = Nothing
  42. Set MsgColl = Nothing
  43. End Sub

    Other things you can do involve incorporating other email properties, such as received time. This will save the filename with date and time pre-pended to the display name:

VBA:
  1. MsgAttach.Item(lAttach).SaveAsFile "C:\My Folder\" & Format(Msg.ReceivedTime, "mmddyyyy hhmm") & " " & FileN

    And this will save the filename as just the received time, with the proper file extension:

VBA:
  1. MsgAttach.Item(lAttach).SaveAsFile "C:\My Folder\" & Format(Msg.ReceivedTime, "mmddyyyy hhmm") & Right$(FileN, 4)

    You can also use the Subject property:

VBA:
  1. MsgAttach.Item(lAttach).SaveAsFile "C:\My Folder\" & Msg.Subject & " " & Format(Msg.ReceivedTime, "mmddyyyy hhmm") & Right$(FileN, 4)

    This will set the attachment filename to Subject and Received time.

Enjoy,
JP


Share and Enjoy:
  • StumbleUpon
  • Technorati
  • Digg
  • Google
  • del.icio.us
  • MisterWong

Print This Post Print This Post  |  Email This Post Email This Post  |  Permalink  |  Subscribe to this feed Subscribe now!

Filed Under: Outlook, VBA
Tags: ,

This post has 90 views since August 25, 2008 – 1:23 pm.

Post a Comment

To post VBA code in your comment, use [VBA] tags, like this: [VBA]Code goes here[/VBA].





Subscribe without commenting

Keep Reading:

Browse Posts:


« Excel, I choose you! || Add your signature to pre-formatted emails »