none
Rename file if filename exists RRS feed

  • Question

  • Hi all,

    I'm new in all to this. I hope someone can help me out. I have a script that allows me to save all PDF attachments from a mail into a specific directory.

    The problem is, when the file allready exists, it simply overwrites the existing file. How can I rewrite the script, so that it checks if the file excists. And if it does it renames it? For example... rename "file.pdf" to "file1.pdf". or to "201308281126file.pdf" (the numbers are todays date and time).

    Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    
    
    
    saveFolder = "S:\NL\"
        For Each objAtt In itm.Attachments
    If (Right(objAtt.FileName, 3) = "pdf") Then
            objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
    
            Set objAtt = Nothing
    End If
        Next
    
    End Sub


    • Edited by Casartelli Wednesday, August 28, 2013 9:33 AM
    Wednesday, August 28, 2013 9:33 AM

Answers

  • Hi Casartelli,

    According to your description, you want to make sure whether the PDF file in attachment has existed in folder before saving the attachment PDF file.

    I wrote a sample added to your codes below.

    Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
    
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    Dim DirFile As String
    
    saveFolder = "S:\NL\"
    
    For Each objAtt In itm.Attachments
    If (Right(objAtt.Filename, 3) = "pdf") Then
        DirFile = saveFolder & "\" & objAtt.DisplayName
        If Dir(DirFile) = "" Then  'the file not exists
            objAtt.SaveAsFile DirFile
        Else
            DirFile = saveFolder & "\" & Replace(objAtt.Filename, ".pdf", "") & Format(Now, "yyyyMMddhhmmss") & ".pdf"
            objAtt.SaveAsFile DirFile
        End If
        Set objAtt = Nothing
    End If
        Next
    End Sub


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.


    Thursday, August 29, 2013 2:46 PM
    Moderator