IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

VBA Outlook Discussion :

Enregistrer les pièces jointes


Sujet :

VBA Outlook

  1. #1
    Futur Membre du Club
    Homme Profil pro
    Rédacteur
    Inscrit en
    Octobre 2019
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Rédacteur

    Informations forums :
    Inscription : Octobre 2019
    Messages : 11
    Points : 8
    Points
    8
    Par défaut Enregistrer les pièces jointes
    Bonjour,

    J'ai vu le modèle de la FAQ ici, mais il me pose un problème : les pièces jointes (des fichiers Excel) ayant des noms de fichiers redondants, ils sont écrasés au fur et à mesure. Je cherche donc à l'adapter.

    Et comme je code avec mes pieds une fois toutes les années bissextiles, je viens demander de l'aide.

    J'imagine que donner un nom de fichier en fonction d'une information se trouvant dans une cellule bien précise du fichier Excel en pièce jointe, risque de compliquer quelque peu la chose, alors faisons simple, je ferais cette modif dans Excel dans un second temps.

    Il faudrait donc que le nom de chaque pièce jointe soit différent et, pour des raisons de traitement, qu'il soit constitué dans cet ordre : de la date du fichier (ou du mail qui la contient) + du nom du fichier + d'une incrémentation.

    Si vous avez des propositions, n'hésitez pas, lancez-vous .

    J'en profite pour vous souhaiter une bonne année, car je suis encore dans les temps.

    Merci par avance

  2. #2
    Futur Membre du Club
    Homme Profil pro
    Rédacteur
    Inscrit en
    Octobre 2019
    Messages
    11
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Seine et Marne (Île de France)

    Informations professionnelles :
    Activité : Rédacteur

    Informations forums :
    Inscription : Octobre 2019
    Messages : 11
    Points : 8
    Points
    8
    Par défaut
    Bonjour,

    La macro de "developpez.net" me posait essentiellement le problème suivant : elle n'incrémente un nombre dans le nom du fichier que pour les images intégrées dans un même corps de mail, ce qui fait qu'au prochain mail traité (puisque la macro peut s'appliquer sur une sélection de plusieurs mails), si des images ont également été intégrées dans le corps du mail suivant, elle viendront écraser celles précédemment enregistrés car enregistrées sous le même nom (image001, immage002, etc.). Je ne sais pas j'ai été très clair...
    Quant aux "vraies" pièces jointes, genre fichier Excel, pas d'incrémentation, les fichiers de même nom sont systématiquement écrasés.

    J'ai trouvé une première solution ici : https://fr.extendoffice.com/document...tachments.html

    L'avantage de cette macro, est qu'elle n'écrase par les pièces jointes portant le même nom (incrémentation).

    Le fichier "mAttachmentSaver.bas" évoqué dans la page web n'est plus disponible sur leur site, mais j'ai pu la récupérer.

    Pour ceux qui seraient intéressés, je le copie ci-dessous.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    Attribute VB_Name = "mAttachmentSaver"
    '---------------------------------------------------------------------------------
    ' The sample scripts are not supported under any Microsoft standard support
    ' program or service. The sample scripts are provided AS IS without warranty
    ' of any kind. Microsoft further disclaims all implied warranties including,
    ' without limitation, any implied warranties of merchantability or of fitness for
    ' a particular purpose. The entire risk arising out of the use or performance of
    ' the sample scripts and documentation remains with you. In no event shall
    ' Microsoft, its authors, or anyone else involved in the creation, production, or
    ' delivery of the scripts be liable for any damages whatsoever (including,
    ' without limitation, damages for loss of business profits, business interruption,
    ' loss of business information, or other pecuniary loss) arising out of the use
    ' of or inability to use the sample scripts or documentation, even if Microsoft
    ' has been advised of the possibility of such damages.
    '---------------------------------------------------------------------------------
     
    Option Explicit
     
    ' *****************
    ' For Outlook 2010.
    ' *****************
    #If VBA7 Then
        ' The window handle of Outlook.
        Private lHwnd As LongPtr
     
        ' /* API declarations. */
        Private Declare PtrSafe Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, _
            ByVal lpWindowName As String) As LongPtr
     
    ' *****************************************
    ' For the previous version of Outlook 2010.
    ' *****************************************
    #Else
        ' The window handle of Outlook.
        Private lHwnd As Long
     
        ' /* API declarations. */
        Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, _
            ByVal lpWindowName As String) As Long
    #End If
     
    ' The class name of Outlook window.
    Private Const olAppCLSN As String = "rctrl_renwnd32"
    ' Windows desktop - the virtual folder that is the root of the namespace.
    Private Const CSIDL_DESKTOP = &H0
    ' Only return file system directories. If the user selects folders that are not part of the file system, the OK button is grayed.
    Private Const BIF_RETURNONLYFSDIRS = &H1
    ' Do not include network folders below the domain level in the dialog box's tree view control.
    Private Const BIF_DONTGOBELOWDOMAIN = &H2
    ' The maximum length for a path is 260 characters.
    Private Const MAX_PATH = 260
     
    ' ######################################################
    '  Returns the number of attachements in the selection.
    ' ######################################################
    Public Function SaveAttachmentsFromSelection() As Long
        Dim objFSO              As Object       ' Computer's file system object.
        Dim objShell            As Object       ' Windows Shell application object.
        Dim objFolder           As Object       ' The selected folder object from Browse for Folder dialog box.
        Dim objItem             As Object       ' A specific member of a Collection object either by position or by key.
        Dim selItems            As Selection    ' A collection of Outlook item objects in a folder.
        Dim atmt                As Attachment   ' A document or link to a document contained in an Outlook item.
        Dim strAtmtPath         As String       ' The full saving path of the attachment.
        Dim strAtmtFullName     As String       ' The full name of an attachment.
        Dim strAtmtName(1)      As String       ' strAtmtName(0): to save the name; strAtmtName(1): to save the file extension. They are separated by dot of an attachment file name.
        Dim strAtmtNameTemp     As String       ' To save a temporary attachment file name.
        Dim intDotPosition      As Integer      ' The dot position in an attachment name.
        Dim atmts               As Attachments  ' A set of Attachment objects that represent the attachments in an Outlook item.
        Dim lCountEachItem      As Long         ' The number of attachments in each Outlook item.
        Dim lCountAllItems      As Long         ' The number of attachments in all Outlook items.
        Dim strFolderPath       As String       ' The selected folder path.
        Dim blnIsEnd            As Boolean      ' End all code execution.
        Dim blnIsSave           As Boolean      ' Consider if it is need to save.
     
        blnIsEnd = False
        blnIsSave = False
        lCountAllItems = 0
     
        On Error Resume Next
     
        Set selItems = ActiveExplorer.Selection
     
        If Err.Number = 0 Then
     
            ' Get the handle of Outlook window.
            lHwnd = FindWindow(olAppCLSN, vbNullString)
     
            If lHwnd <> 0 Then
     
                ' /* Create a Shell application object to pop-up BrowseForFolder dialog box. */
                Set objShell = CreateObject("Shell.Application")
                Set objFSO = CreateObject("Scripting.FileSystemObject")
                Set objFolder = objShell.BrowseForFolder(lHwnd, "Select folder to save attachments:", _
                                                         BIF_RETURNONLYFSDIRS + BIF_DONTGOBELOWDOMAIN, CSIDL_DESKTOP)
     
                ' /* Failed to create the Shell application. */
                If Err.Number <> 0 Then
                    MsgBox "Run-time error '" & CStr(Err.Number) & " (0x" & CStr(Hex(Err.Number)) & ")':" & vbNewLine & _
                           Err.Description & ".", vbCritical, "Error from Attachment Saver"
                    blnIsEnd = True
                    GoTo PROC_EXIT
                End If
     
                If objFolder Is Nothing Then
                    strFolderPath = ""
                    blnIsEnd = True
                    GoTo PROC_EXIT
                Else
                    strFolderPath = CGPath(objFolder.Self.Path)
     
                    ' /* Go through each item in the selection. */
                    For Each objItem In selItems
                        lCountEachItem = objItem.Attachments.Count
     
                        ' /* If the current item contains attachments. */
                        If lCountEachItem > 0 Then
                            Set atmts = objItem.Attachments
     
                            ' /* Go through each attachment in the current item. */
                            For Each atmt In atmts
     
                                ' Get the full name of the current attachment.
                                strAtmtFullName = atmt.FileName
     
                                ' Find the dot postion in atmtFullName.
                                intDotPosition = InStrRev(strAtmtFullName, ".")
     
                                ' Get the name.
                                strAtmtName(0) = Left$(strAtmtFullName, intDotPosition - 1)
                                ' Get the file extension.
                                strAtmtName(1) = Right$(strAtmtFullName, Len(strAtmtFullName) - intDotPosition)
                                ' Get the full saving path of the current attachment.
                                strAtmtPath = strFolderPath & atmt.FileName
     
                                ' /* If the length of the saving path is not larger than 260 characters.*/
                                If Len(strAtmtPath) <= MAX_PATH Then
                                    ' True: This attachment can be saved.
                                    blnIsSave = True
     
                                    ' /* Loop until getting the file name which does not exist in the folder. */
                                    Do While objFSO.FileExists(strAtmtPath)
                                        strAtmtNameTemp = strAtmtName(0) & _
                                                          Format(Now, "_mmddhhmmss") & _
                                                          Format(Timer * 1000 Mod 1000, "000")
                                        strAtmtPath = strFolderPath & strAtmtNameTemp & "." & strAtmtName(1)
     
                                        ' /* If the length of the saving path is over 260 characters.*/
                                        If Len(strAtmtPath) > MAX_PATH Then
                                            lCountEachItem = lCountEachItem - 1
                                            ' False: This attachment cannot be saved.
                                            blnIsSave = False
                                            Exit Do
                                        End If
                                    Loop
     
                                    ' /* Save the current attachment if it is a valid file name. */
                                    If blnIsSave Then atmt.SaveAsFile strAtmtPath
                                Else
                                    lCountEachItem = lCountEachItem - 1
                                End If
                            Next
                        End If
     
                        ' Count the number of attachments in all Outlook items.
                        lCountAllItems = lCountAllItems + lCountEachItem
                    Next
                End If
            Else
                MsgBox "Failed to get the handle of Outlook window!", vbCritical, "Error from Attachment Saver"
                blnIsEnd = True
                GoTo PROC_EXIT
            End If
     
        ' /* For run-time error:
        '    The Explorer has been closed and cannot be used for further operations.
        '    Review your code and restart Outlook. */
        Else
            MsgBox "Please select an Outlook item at least.", vbExclamation, "Message from Attachment Saver"
            blnIsEnd = True
        End If
     
    PROC_EXIT:
        SaveAttachmentsFromSelection = lCountAllItems
     
        ' /* Release memory. */
        If Not (objFSO Is Nothing) Then Set objFSO = Nothing
        If Not (objItem Is Nothing) Then Set objItem = Nothing
        If Not (selItems Is Nothing) Then Set selItems = Nothing
        If Not (atmt Is Nothing) Then Set atmt = Nothing
        If Not (atmts Is Nothing) Then Set atmts = Nothing
     
        ' /* End all code execution if the value of blnIsEnd is True. */
        If blnIsEnd Then End
    End Function
     
    ' #####################
    ' Convert general path.
    ' #####################
    Public Function CGPath(ByVal Path As String) As String
        If Right(Path, 1) <> "\" Then Path = Path & "\"
        CGPath = Path
    End Function
     
    ' ######################################
    ' Run this macro for saving attachments.
    ' ######################################
    Public Sub ExecuteSaving()
        Dim lNum As Long
     
        lNum = SaveAttachmentsFromSelection
     
        If lNum > 0 Then
            MsgBox CStr(lNum) & " attachment(s) was(were) saved successfully.", vbInformation, "Message from Attachment Saver"
        Else
            MsgBox "No attachment(s) in the selected Outlook items.", vbInformation, "Message from Attachment Saver"
        End If
    End Sub
    Pour lancer la macro, sélectionner celle nommée "ExecuteSaving".

    Il me reste à trouver comment faire (sous Excel cette fois) pour ajouter au nom de chaque fichier la date contenue dans une cellule du fichier en question, ou mieux : la dernière date de modification...

    Si vous avez des idées, n'hésitez pas.

    A++

Discussions similaires

  1. Réponses: 2
    Dernier message: 27/01/2015, 19h02
  2. Réponses: 0
    Dernier message: 18/01/2015, 11h59
  3. Réponses: 0
    Dernier message: 21/11/2012, 17h52
  4. Enregistrer les pièces jointes Outlook Express
    Par kervin dans le forum VBA Access
    Réponses: 6
    Dernier message: 16/12/2010, 17h49
  5. enregistrer les pièces jointes outlook selon un objet
    Par tibofo dans le forum VB 6 et antérieur
    Réponses: 1
    Dernier message: 08/05/2009, 18h02

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo