Consulting

Results 1 to 2 of 2

Thread: Outlook Save attachment and rename file with Subject

  1. #1
    VBAX Newbie
    Joined
    Dec 2015
    Posts
    1
    Location

    Outlook Save attachment and rename file with Subject

    Hi All,

    please help with code below as I've scattered it around and found.

    What I am trying to do is: select emails with attachment in Outlook and then extract the attached files then rename the files with the subject line.

    this is what I have but its not 100% working yet. Sample() extracts the file GetValidName() function checks if the subject line had invalid characters.




    Sub Sample()
    Dim selectedEmail As Outlook.Attachment
    Dim emailsub As String


    Dim itm As Outlook.MailItem
    Dim currentExplorer As Explorer
    Dim Selection As Selection

    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    Dim fso As Object
    Dim oldName

    Dim file As String
    Dim DateFormat As String
    Dim newName As String

    Dim enviro As String
    enviro = CStr(Environ("USERPROFILE"))
    'saveFolder = enviro & "\Documents\Attachments\"
    saveFolder = "C:\Temp"

    Set currentExplorer = Application.ActiveExplorer
    Set Selection = currentExplorer.Selection


    Set selectedEmail = ActiveExplorer.Selection.Item(1)

    emailsub = GetValidName(objAtt.Subject)

    'Debug.Print emailsub

    With selectedEmail
    .SaveAs "C:\Temp" & emailsub & ".pdf", 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

  2. #2
    See the thread - http://www.vbaexpress.com/forum/show...-Message-Macro which is very similar to your requirement, and has a more useful naming structure. It also includes code for ensuring duplicated filenames are not overwritten.
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •