Home » excel » excel – Extract attachments from saved .msg files using VBA

excel – Extract attachments from saved .msg files using VBA

Posted by: admin April 10, 2020 Leave a comment

Questions:

I am trying to extract attached Excel spreadsheets from saved Outlook messages. The messages have been saved into a shared folder as .msg files.

I am struggling to get VBA to recognise the messages as files.

I am trying to get the message details in the code below as a proof of concept.

Once I have this working I can work on looping through the files and dealing with the attachments.

I have found code on this site for extracting attachments from emails still in Outlook but I do not have access to the Outlook folders and the original messages have been deleted.

Sub ExtractExcel()
Dim aExcel As Outlook.Attachment
Dim stFilePath As String
Dim stFileName As String
Dim stAttName As String
Dim stSaveFolder As String
Dim oEmail As Outlook.MailItem

'~~> Outlook Variables for email
Dim eSender As String, dtRecvd As String, dtSent As String
Dim sSubj As String, sMsg As String

stFilePath = "Y:\Purchasing\The Team\User Name\Supply Chain Admin - Outlook\New-Revised Orders\FW  Mail Order Daffodil.msg"
stSaveFolder = "C:\Projects\SOTD\PO_Excel"

Debug.Print stFilePath
Debug.Print stSaveFolder

oEmail = stFilePath

With oEmail 
    eSender = oEmail.SenderEmailAddress
    dtRecvd = oEmail.ReceivedTime
    dtSent = oEmail.CreationTime
    sSubj = oEmail.Subject
    sMsg = oEmail.Body

    Debug.Print eSender
    Debug.Print dtRecvd
    Debug.Print dtSent
    Debug.Print sSubj
    Debug.Print sMsg
End With

End Sub

I’m using Excel VBA as I am familiar with it but am happy to have any alternative strategies suggested.

How to&Answers:

Using CreateItemFromTemplate from VBA Code to save an attachment (excel file) from an Outlook email that was inside another email as an attachment you could

  • open msg files from C:\temp\
  • strip all attachments to C:\temp1\

code

Sub SaveOlAttachments()

Dim msg As Outlook.MailItem
Dim att As Outlook.Attachment
Dim strFilePath As String
Dim strAttPath As String

    'path for creating msgs
strFilePath = "C:\temp\"
    'path for saving attachments
strAttPath = "C:\temp1\"

strFile = Dir(strFilePath & "*.msg")
Do While Len(strFile) > 0
    Set msg = Application.CreateItemFromTemplate(strFilePath & strFile)
    If msg.Attachments.Count > 0 Then
         For Each att In msg.Attachments
             att.SaveAsFile strAttPath & att.FileName
         Next
    End If
    strFile = Dir
Loop

End Sub

Answer:

I have a VBS script that I use to extract all XLS* attachments form msg files saved in a folder. This script save the attachments in the same folder of msg files. I believe that can help you.

Macro.vbs

'Variables
Dim ol, fso, folderPath, destPath, f, msg, i
'Loading objects
Set ol  = CreateObject("Outlook.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
'Setting MSG files path
folderPath = fso.GetParentFolderName(WScript.ScriptFullName)
'Setting destination path
destPath = folderPath   '* I am using the same 
WScript.Echo "==> "& folderPath
'Looping for files
For Each f In fso.GetFolder(folderPath).Files
    'Filtering only MSG files
    If LCase(fso.GetExtensionName(f)) = "msg" Then
        'Opening the file
        Set msg = ol.CreateItemFromTemplate(f.Path)
        'Checking if there are attachments
        If msg.Attachments.Count > 0 Then
            'Looping for attachments
            For i = 1 To msg.Attachments.Count
                'Checking if is a Excel file
                If LCase(Mid(msg.Attachments(i).FileName, InStrRev(msg.Attachments(i).FileName, ".") + 1 , 3)) = "xls" Then
                    WScript.Echo f.Name &" -> "& msg.Attachments(i).FileName
                    'Saving the attachment
                    msg.Attachments(i).SaveAsFile destPath &"\"& msg.Attachments(i).FileName
                End If
            Next
        End If
    End If
Next
MsgBox "Anexos extraidos com sucesso!"

To execute use “cscript c:\temp\msg_files\Macro.vbs” in command prompt.

Answer:

Use Namespace.OpenSharedItem. Do not use CreateItemFromTemplate – it wipes out many properties (such as sender and receiver related properties).

Answer:

I changed this code so that you can extract attachments from Excel instead of outlook.

Don’t forget to reference the Outlook Library, otherwise you will get the error

Sub SaveOlAttachments()

Dim app As Outlook.Application
Dim msg As Outlook.MailItem
Dim att As Outlook.Attachment
Dim strFilePath As String
Dim strAttPath As String

Set app = New Outlook.Application

'path for creating msgs
strFilePath = "C:\Users\New folder\"

'path for saving attachments
strAttPath = "C:\Users\Extract\"

strFile = Dir(strFilePath & "*.msg")

Do While Len(strFile) > 0
    Set msg = app.CreateItemFromTemplate(strFilePath & strFile)
    If msg.Attachments.Count > 0 Then
         For Each att In msg.Attachments
             att.SaveAsFile strAttPath & att.Filename
         Next
    End If
    strFile = Dir
Loop

MsgBox "Task Completed", vbInformation

End Sub