Search code examples
vbaoutlookoutlook-2010

Attachments are missing in outlook 2010


I wrote some VBA macro to download all the attachments of my outlook.I used the following code to achieve that:

Public Sub SaveAttachments()
  Dim objOL As Outlook.Application
  Dim objMsg As Outlook.MailItem
  Dim objAttachments As Outlook.Attachments
  Dim objSelection As Outlook.Selection
  Dim i As Long
  Dim lngCount As Long
  Dim strFile As String
  Dim strFolderpath As String
  Dim strDeletedFiles As String
  strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
  On Error Resume Next
  Set objOL = CreateObject("Outlook.Application")
  Set objSelection = objOL.ActiveExplorer.Selection
  strFolderpath = strFolderpath & "\Attachments\"
  For Each objMsg In objSelection
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFiles = ""
    If lngCount > 0 Then
      For i = lngCount To 1 Step -1
        strFile = objAttachments.Item(i).FileName
        strFile = strFolderpath & strFile
        objAttachments.Item(i).SaveAsFile strFile
        objAttachments.Item(i).Delete
        If objMsg.BodyFormat <> olFormatHTML Then
          strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile _
            & ">"
        Else
          strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" _
            & strFile & "'>" & strFile & "</a>"
        End If
      Next i
      If objMsg.BodyFormat <> olFormatHTML Then
        objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles _
          & vbCrLf & objMsg.Body
      Else
        objMsg.HTMLBody = "<p>" & "The file(s) were saved to " _
          & strDeletedFiles & "</p>" & objMsg.HTMLBody
      End If
      objMsg.Save
    End If
  Next
  ExitSub:
  Set objAttachments = Nothing
  Set objMsg = Nothing
  Set objSelection = Nothing
  Set objOL = Nothing
End Sub

It was run successfully.

But I could not find that folder in my system. I was trying to open in mail at least, but it was saying that the attachment has been saved to C:\xxxx..... folder which actually does not exist in my system. I need those attachments and they are very important.

Is there any way to restore those mail attachments. (I guess, attachments have been deleted from the server itself, since there was a statement in mycode objAttachments.Item(i).Delete).


Solution

  • Most likely your procedure encountered an error when trying to save the attachments to a non-existent folder, since the code doesn't bother checking if saving the attachment is successful or if the folder exists in the first place. However, the error was suppressed by the On Error Resume Next, so the code continued to deleting the attachments, even though they hadn't been saved. Unless you have a backup, the attachments are probably lost.

    NEVER use On Error Resume Next unless you know exactly what you're doing and have sensible error-handling code in place.