Ergin
Ergin

Reputation: 43

Outlook macro for moving message to HDD works but opening the message gives error

I have an Outlook macro to move incoming message to HDD via Outlook rules and it works fine.

But problem is when I open the message on HDD copied via macro, I get this error message

"We can't open xxxxx. It's possible the file is already open, or you don't have permission to open it. To check your permissions, right-click the file folder, then click Properties."

I checked my permissions and found no problem. I also closed Outlook and try to open the saved message but nothing changed, I still get same error message.

How can we solve this error ?

Public Sub AutoSave(oMail As Outlook.MailItem)
    Dim dtDate As Date
    Dim sName As String
    Dim sFile As String
    Dim sExt As String

    sPath = "C:\Users\xxxuser\Desktop\"
    sExt = ".msg"
    sName = oMail.Subject
    ReplaceCharsForFileName sName, "_"
    dtDate = oMail.ReceivedTime
    sName = Format(dtDate, "yyyymmdd", vbUseSystemDayOfWeek, _
    vbUseSystem) & Format(dtDate, "-hhnnss", _
    vbUseSystemDayOfWeek, vbUseSystem) & "-" & sName & sExt

    oMail.SaveAs sPath & sName, olSaveAsMsg

End Sub

Public Sub ReplaceCharsForFileName(sName As String, _
    sChr As String _
    )
    sName = Replace(sName, "/", sChr)
    sName = Replace(sName, "", sChr)
    sName = Replace(sName, "FW:", sChr)
    sName = Replace(sName, "RE:", 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

Upvotes: 1

Views: 142

Answers (1)

Pᴇʜ
Pᴇʜ

Reputation: 57683

I think olSaveAsMsg is wrong and because you didn't use Option Explicit you didn't see that. So I recommend to write Option Explicit at the top of your module. Then you will see that olSaveAsMsg is considered as variable and it is not declared.
It should now throw an error "Variable is not defined".

Because the empty variable probably casts to 0 which means olTXT according to OlSaveAsType Enumeration, it is very likely that your message is saved in text format, and therefore Outlook can not open it.

So save it in the Outlook message format it should be

  • olMSG for "Outlook message format" or
  • olMSGUnicode for "Outlook Unicode message format".

Upvotes: 2

Related Questions