Save selected messages to MSG files

In Save selected email message as .msg file, Outlook MVP Diane Poremsky shows us how to save selected messages as .MSG files on the local computer.

Do people really do this? Nevermind.

I think the code could be improved. For starters, it assumes that all selected items are mail items. I have no problem with that per se, but it should be stated as a caveat in the article.

Also, it hardcodes the path to the My Documents folder. I don't know about you, but on my computer the folder name is "My Documents" not "Documents". So the code doesn't scale.

I used the code I found here to programmatically determine the My Documents folder. Here is what I came up with:

Public Sub SaveMessagesAsMsg()

  Dim obj As Object
  Dim msg As Outlook.MailItem
  Dim objWSHShell As Object
  Dim mydocpath As String
  Dim filename As String

  If ActiveExplorer.Selection.Count > 0 Then
    Set objWSHShell = CreateObject("WScript.Shell")
    mydocpath = objWSHShell.SpecialFolders("MyDocuments") & "\"

    For Each obj In ActiveExplorer.Selection
      If TypeName(obj) = "MailItem" Then
        Set msg = obj

        filename = _
        ReplaceCharsForFileName(Format(msg.ReceivedTime, "yyyymmdd-hhmmss", _
            vbUseSystemDayOfWeek, vbUseSystem) & _
            "-" & msg.Subject) & ".msg"
        msg.SaveAs mydocpath & filename, olMSG
      End If
    Next obj
  End If

End Sub

Function ReplaceCharsForFileName(sName As String, _
   Optional sChr As String = "_") As String
' replace illegal filename characters
   sName = Replace(sName, "/", sChr)
   sName = Replace(sName, "\", sChr)
   sName = Replace(sName, ":", sChr)
   sName = Replace(sName, "?", sChr)
   sName = Replace(sName, Chr(34), sChr)
   sName = Replace(sName, "<", sChr)
   sName = Replace(sName, ">", sChr)
   sName = Replace(sName, "|", sChr)
End Sub

Benefits

  • No hardcoding of documents path
  • Code is shorter
  • Assume underscore is replacement character instead of forcing user to specify it
About JP

I'm just an average guy who writes VBA code for a living. This is my personal blog. Excel and Outlook are my thing, with a sprinkle of Access and Word here and there. Follow this space to learn more about VBA. Keep Reading »


Related Articles:


Share This Article:

Share and bookmark this articledelicious buttonfacebook buttonlinkedin buttonstumbleupon buttontwitter button

This article is closed to any future comments.
learn excel dashboards