lundi 15 février 2021

How to saveas with specific name file already exist

I have an issue, I want to extract Attachements from a shared mail box in VBA. BUT if the file already exist in my folder, I wan't to have an incremental variable at the end ... So it will give something like this: Mail received: -Attachement : azerty.pdf send the 15/02/2021 at 09:13 ( sometimes 2 mails with the same name can be send at the same time) The downloaded file name: azerty_2021-0215-0913.pdf

if the file already exist in my folder : azerty_2021-0215-0913_N.pdf ( N= N+1)

This is what i've did so far:

Sub ExtrairePJ_Mail()
    'Déclaation des variables.
    'Variable concernant l'extraction
    Dim oMail As MailItem
    Dim myFolder As Folder
    Dim myOlApp As Outlook.Application
    Dim myNamespace As Namespace
    Dim myRecipient As Outlook.recipient
    Dim oAttachement As Attachment
    Dim myFile As Object
    
    'Variable Concernant l'existance de fichier
    Dim strName As String

    
    ' variables liées à Outlook.
    Set myOlApp = CreateObject("Outlook.Application")
    Set myNamespace = myOlApp.GetNamespace("MAPI")
    Set myRecipient = myNamespace.CreateRecipient("IT.SECURITY CONTROLS (FR)")
    Set myFolder = myNamespace.GetSharedDefaultFolder(myRecipient, olFolderInbox)
    
    'Variable modiafiable.
    n = 1 'Numéro en cas d'existance de fichier.
    FolderPath = "PATH"  'Chemin du dossier où l'on souhaite sauvegarder le fichier
    
    'Boucle parcourant la boite mail
    For Each oMail In myFolder.Items
        'Condition vérifiant si l'objet est "AUD_ACTTER Reports the active terminals of users who did not sign off properly"
        'If oMail.subject Like "*" & "AUD_ACTTER Reports the active terminals of users who did not sign off properly" & "*" Then
        
        If oMail.subject Like "*" & "TEST NE PAS SUPPRIMER" & "*" Then
            
            'Debug.Print oMail.subject & "-" & Format(oMail.ReceivedTime, "yyyy-mmdd-hhnn") & "_" & n
            For Each oAttachement In oMail.Attachments
                strName = Split(oAttachement.DisplayName, ".")(0)
                If Dir(FolderPath & strName & "_" & Format(oMail.ReceivedTime, "yyyy-mmdd-hhnn") & ".pdf") = "" Then
                    oAttachement.SaveAsFile FolderPath & oAttachement.Filename & "_" & Format(oMail.ReceivedTime, "yyyy-mmdd-hhnn") & ".pdf"
                   
                Else
                    
                    oAttachement.SaveAsFile FolderPath & oAttachement.Filename & "_" & Format(oMail.ReceivedTime, "yyyy-mmdd-hhnn") & "_" & n & ".pdf"
                    n = n + 1
                End If
                
            Next oAttachement
            Set oAttachement = Nothing
        End If
    Next oMail
   
End Sub

Can you please help me ? Right now my code doesn't enter in the else condition

Aucun commentaire:

Enregistrer un commentaire