使用主题作为文件名保存邮件

时间:2013-10-10 09:20:48

标签: outlook-2010 outlook-vba

早上好,

我希望有人能用一段代码帮助我。

我希望将选定的电子邮件保存到特定目录,其中包含电子邮件的名称,当然还有.msg文件。 这就是我今天所拥有的,它不起作用。它保存了一个文件,但名称只有前2个字符(在半冒号文件名之后看起来像是错误,例如:FW或RE)......文件内容为空白且文件类型尚未应用。

'code to save selected email
Dim selectedEmail As MailItem
Set selectedEmail = ActiveExplorer.Selection.Item(1)
Dim emailsub As String
emailsub = ActiveExplorer.Selection.Item(1).Subject
    With selectedEmail
        .SaveAs "C:\direcotry\folder\" & emailsub & ".msg", olMSG
    End With

感谢您的期待。 DOM

1 个答案:

答案 0 :(得分:2)

原因很简单。您发送电子邮件主题包含和无效字符。例如:这通常发生在电子邮件为RE:FWD:

试试这个

Sub Sample()
    Dim selectedEmail As MailItem
    Dim emailsub As String

    Set selectedEmail = ActiveExplorer.Selection.Item(1)

    emailsub = GetValidName(selectedEmail.subject)

    'Debug.Print emailsub

    With selectedEmail
        .SaveAs "C:\direcotry\folder\" & emailsub & ".msg", OlSaveAsType.olMSG
    End With
End Sub

Function GetValidName(sSub As String) As String
    '~~> File Name cannot have these \ / : * ? " < > |
    Dim sTemp As String

    sTemp = sSub

    sTemp = Replace(sTemp, "\", "")
    sTemp = Replace(sTemp, "/", "")
    sTemp = Replace(sTemp, ":", "")
    sTemp = Replace(sTemp, "*", "")
    sTemp = Replace(sTemp, """", "")
    sTemp = Replace(sTemp, "<", "")
    sTemp = Replace(sTemp, ">", "")
    sTemp = Replace(sTemp, "|", "")

    GetValidName = sTemp
End Function