Saving emails with sender's initials

旧时模样 提交于 2021-01-29 07:51:01

问题


I am trying to save emails as .msg files.

I am using the following code, resulting in the filename format "yyyy-mm-dd - sender - title.msg". I need the sender's initials instead of the whole name.

Sub OpenAndSave()
    Const SAVE_TO_FOLDER = "C:\Users\Documents\Emails\"
    Dim olkMsg As Outlook.MailItem, intCount As Integer
    intCount = 1
    For Each olkMsg In Outlook.ActiveExplorer.Selection
        strDate = Format(olkMsg.ReceivedTime, "yyyy-mm-dd - ")
        olkMsg.Display
        olkMsg.SaveAs SAVE_TO_FOLDER & strDate & RemoveIllegalCharacters(olkMsg.senderName) & " - " & RemoveIllegalCharacters(olkMsg.Subject) & ".msg"
        olkMsg.Close olDiscard
    Next
    Set olkMsg = Nothing
End Sub

Function RemoveIllegalCharacters(strValue As String) As String
    ' Purpose: Remove characters that cannot be in a filename from a string.'
    RemoveIllegalCharacters = strValue
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, "<", "")
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, ">", "")
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, ":", "")
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, Chr(34), "'")
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, "/", "")
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, "\", "")
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, "|", "")
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, "?", "")
    RemoveIllegalCharacters = Replace(RemoveIllegalCharacters, "*", "")
End Function

E.g. email from John A Smith today: “2019-10-23 - JAS - Subject” Or email from Kevin Bishop yesterday: “2019-10-22 - KB - Subject”


回答1:


You could use a helper function like this perhaps to return the initials from the sender name:

Private Function Initials(ByVal fullName As String) As String
    Dim splitName
    splitName = Split(fullName)

    Dim i As Long
    For i = LBound(splitName) To UBound(splitName)
        Initials = UCase$(Initials & IIf(Len(splitName(i) > 0), Left$(splitName(i), 1), ""))
    Next
End Function

Call it perhaps like this:

olkMsg.SaveAs SAVE_TO_FOLDER & strDate & RemoveIllegalCharacters(Initials(olkMsg.senderName))...

though I would break that up into multiple pieces for readability.

EDIT:

You can probably simplify the Initials = ... line to:

Initials = UCase$(Initials & Left$(splitName(i), 1))


来源:https://stackoverflow.com/questions/58529914/saving-emails-with-senders-initials

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!