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

Contribuez Discussion :

Lister les fichiers d'un répertoire dans une feuille Excel [À publier]


Sujet :

Contribuez

  1. #1
    Modérateur
    Avatar de AlainTech
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Mai 2005
    Messages
    4 235
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 71
    Localisation : Belgique

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Mai 2005
    Messages : 4 235
    Par défaut Lister les fichiers d'un répertoire dans une feuille Excel
    Suite à cette question, je me suis basé sur le contenu de cette discussion (merci à SilkyRoad) pour charger, dans une feuille Excel, le contenu d'un répertoire (avec les sous-répertoires).

    La routine:
    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
    Option Explicit
     
    Sub ListFilesInFolder(strFolderName As String, bIncludeSubfolders As Boolean)
      ' adapté de Ole P Erlandsen
      ' necessite d'activer la reference Microsoft Scripting RunTime
      Static FSO As FileSystemObject
      Dim oSourceFolder As Scripting.Folder
      Dim oSubFolder As Scripting.Folder
      Dim oFile As Scripting.File
      Static wksDest As Worksheet
      Static iRow As Long
      Static bNotFirstTime As Boolean
     
      If Not bNotFirstTime Then
        Set wksDest = ActiveSheet ' A adtapter
        Set FSO = CreateObject("Scripting.FileSystemObject")
        With wksDest
          .Cells(1, 1) = "Parent folder"
          .Cells(1, 2) = "Full path"
          .Cells(1, 3) = "File name"
          .Cells(1, 4) = "Size"
          .Cells(1, 5) = "Type"
          .Cells(1, 6) = "Date created"
          .Cells(1, 7) = "Date last modified"
          .Cells(1, 8) = "Date last accessed"
          .Cells(1, 9) = "Attributes"
          .Cells(1, 10) = "Short path"
          .Cells(1, 11) = "Short name"
        End With
        iRow = 2
        bNotFirstTime = True
      End If
      Set oSourceFolder = FSO.GetFolder(strFolderName)
      For Each oFile In oSourceFolder.Files
        With wksDest
          .Cells(iRow, 1) = oFile.ParentFolder.Path
          .Cells(iRow, 2) = oFile.Path
          .Cells(iRow, 3) = oFile.Name
          .Cells(iRow, 4) = oFile.Size
          .Cells(iRow, 5) = oFile.Type
          .Cells(iRow, 6) = oFile.DateCreated
          .Cells(iRow, 7) = oFile.DateLastModified
          .Cells(iRow, 8) = oFile.DateLastAccessed
          .Cells(iRow, 9) = oFile.Attributes
          .Cells(iRow, 10) = oFile.ShortPath
          .Cells(iRow, 11) = oFile.ShortName
        End With
        iRow = iRow + 1
      Next oFile
     
      For Each oSubFolder In oSourceFolder.SubFolders
        ' On peut mettre ici un traitement spécifique pour les dossiers
      Next oSubFolder
     
      If bIncludeSubfolders Then
        For Each oSubFolder In oSourceFolder.SubFolders
          ListFilesInFolder oSubFolder.Path, True
        Next oSubFolder
      End If
     
    End Sub
    Et son appel:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Private Sub test()
      ListFilesInFolder "D:\My Documents\Access", True
    End Sub
    Edit 17/01/2007 -> Petite modification du code. Dans la première version, je repartais de la ligne 2 à chaque entrée dans la fonction.
    Edit 16/03/2015 -> Optimisation: Utilisation de With - End With.
    N'oubliez pas de cliquer sur quand vous avez obtenu ou trouvé vous-même la réponse à votre question.
    Si vous trouvez seul, pensez à poster votre solution. Elle peut servir à d'autres!
    Pensez aussi à voter pour les réponses qui vous ont aidés.
    ------------
    Je dois beaucoup de mes connaissances à mes erreurs!

  2. #2
    Expert confirmé
    Avatar de ThierryAIM
    Homme Profil pro
    Inscrit en
    Septembre 2002
    Messages
    3 673
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 62
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2002
    Messages : 3 673
    Par défaut
    Citation Envoyé par AlainTech
    J'y reviendrai, sans doute, ajouter d'autres infos que le path.
    Si tu y reviens, previens lorsque c'est finalisé, et j'intègre à la FAQ VBA

  3. #3
    Modérateur
    Avatar de AlainTech
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Mai 2005
    Messages
    4 235
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 71
    Localisation : Belgique

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Finance

    Informations forums :
    Inscription : Mai 2005
    Messages : 4 235
    Par défaut
    Comme promis:
    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
    Option Explicit
     
    Sub ListFilesInFolder(strFolderName As String, bIncludeSubfolders As Boolean)
      ' adapté de Ole P Erlandsen
      ' necessite d'activer la reference Microsoft Scripting RunTime
      Static FSO As FileSystemObject
      Dim oSourceFolder As Scripting.Folder
      Dim oSubFolder As Scripting.Folder
      Dim oFile As Scripting.File
      Static wksDest As Worksheet
      Static iRow As Long
      Static bNotFirstTime As Boolean
     
      If Not bNotFirstTime Then
        Set wksDest = ActiveSheet
        Set FSO = CreateObject("Scripting.FileSystemObject")
        wksDest.Cells(1, 1) = "Parent folder"
        wksDest.Cells(1, 2) = "Full path"
        wksDest.Cells(1, 3) = "File name"
        wksDest.Cells(1, 4) = "Size"
        wksDest.Cells(1, 5) = "Type"
        wksDest.Cells(1, 6) = "Date created"
        wksDest.Cells(1, 7) = "Date last modified"
        wksDest.Cells(1, 8) = "Date last accessed"
        wksDest.Cells(1, 9) = "Attributes"
        wksDest.Cells(1, 10) = "Short path"
        wksDest.Cells(1, 11) = "Short name"
     
        iRow = 2
        bNotFirstTime = True
      End If
      Set oSourceFolder = FSO.GetFolder(strFolderName)
      For Each oFile In oSourceFolder.Files
        wksDest.Cells(iRow, 1) = oFile.ParentFolder.Path
        wksDest.Cells(iRow, 2) = oFile.Path
        wksDest.Cells(iRow, 3) = oFile.Name
        wksDest.Cells(iRow, 4) = oFile.Size
        wksDest.Cells(iRow, 5) = oFile.Type
        wksDest.Cells(iRow, 6) = oFile.DateCreated
        wksDest.Cells(iRow, 7) = oFile.DateLastModified
        wksDest.Cells(iRow, 8) = oFile.DateLastAccessed
        wksDest.Cells(iRow, 9) = oFile.Attributes
        wksDest.Cells(iRow, 10) = oFile.ShortPath
        wksDest.Cells(iRow, 11) = oFile.ShortName
     
        iRow = iRow + 1
      Next oFile
     
      For Each oSubFolder In oSourceFolder.SubFolders
        ' On peut mettre ici un traitement spécifique pour les dossiers
      Next oSubFolder
     
      If bIncludeSubfolders Then
        For Each oSubFolder In oSourceFolder.SubFolders
          ListFilesInFolder oSubFolder.Path, True
        Next oSubFolder
      End If
     
    End Sub
    Je n'ai pas traité l'analyse des flags d'attributs.
    Ca pourrait faire l'objet d'une autre source.

    Edit --> j'ai recopié ce code dans le premier message
    N'oubliez pas de cliquer sur quand vous avez obtenu ou trouvé vous-même la réponse à votre question.
    Si vous trouvez seul, pensez à poster votre solution. Elle peut servir à d'autres!
    Pensez aussi à voter pour les réponses qui vous ont aidés.
    ------------
    Je dois beaucoup de mes connaissances à mes erreurs!

  4. #4
    Membre confirmé
    Homme Profil pro
    Ingénieur acousticien
    Inscrit en
    Septembre 2015
    Messages
    122
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Ingénieur acousticien
    Secteur : Bâtiment Travaux Publics

    Informations forums :
    Inscription : Septembre 2015
    Messages : 122
    Par défaut
    Bonjour AlainTech et merci pour la proposition de cette fonction !

    Je souhaiterais savoir si certaines lignes pourraient particulièrement poser problème pour une recherche sur serveur (je n'avais jamais utilisé d'objet scripting...) ?

    En effet ces lignes de codes fonctionnent parfaitement sur mon poste mais Excel plante dès que je tente de travailler sur un réseau...

    Merci d'avance pour vos éléments.

  5. #5
    Nouveau candidat au Club
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Novembre 2024
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Consultant informatique

    Informations forums :
    Inscription : Novembre 2024
    Messages : 2
    Par défaut
    Bonjour,

    Cette discussion date un peu mais si le code n’est pas dépassé, et que cela peut être utile, je propose ci-dessous une autre version du code.
    L’idée étant de plutôt que d’alimenter des champs dans Excel, alimenter un tableau qu’on passe en paramètre, afin d’avoir une procédure générique réutilisable qui n’a pas à être adapté à chaque cas, mais de traiter le tableau résultat au cas par cas.
    Dans cette logique, il y a un autre paramètre pour déterminer le nombre de champ qu’on veut récupérer (ordre fixe).
    Et une variable pour que le tableau commence au niveau 1, sinon avec la variable i en Static si on réutilise plusieurs fois la fonction dans la même session, la valeur basse (LBound) du tableau suivrait la fin du tableau généré précédemment.
    J’ai aussi rajouté une barre d’avancement (Application.StatusBar)

    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
    Option Explicit
     
    Sub ListFilesInFolder(strFolderName As String, bIncludeSubfolders As Boolean, bUpperCall As Boolean, Num_Detail As Integer, Files_List() As String)
    ' Code adapted from https://www.developpez.net/forums/d200523/logiciels/microsoft-office/excel/contribuez/lister-fichiers-d-repertoire-feuille-excel/
    ' Need to activate the reference Microsoft Scripting RunTime, to do in case of error
    ' To be used this way
    ' Dim Files() As String
    ' Call ListFilesInFolder(Folder_To_Search, True, True, 6, Files)
    ' Second parameter to false if you only want to list on the folder and not it subfolders, third parameter alway put true
    ' 4th parameter from 1 to 10 is the number of columns informations to get. From 1 to 6 is about same performance, from 7 it's quite slower
     
    ' Browse of the folder
    Static FSO As FileSystemObject
    Dim oSourceFolder As Scripting.Folder, oSubFolder As Scripting.Folder
    Dim oFile As Scripting.File
    ' Static bNotFirstTime As Boolean defining it here was problematic when re-executing, so we pass it as a parameter
    Static i As Long
     
    ' If Not bNotFirstTime Then
    If bUpperCall Then
        Set FSO = CreateObject("Scripting.FileSystemObject")
        i = 0
        'bNotFirstTime = True
    End If
     
    On Error GoTo ErrorHandler
    Set oSourceFolder = FSO.GetFolder(strFolderName)
    For Each oFile In oSourceFolder.Files
        i = i + 1
        ReDim Preserve Files_List(1 To Num_Detail, 1 To i)
        'Files_List(0, i) = oFile.Path ' "Full path"
        If Num_Detail >= 1 Then
            Files_List(1, i) = oFile.ParentFolder.Path ' "Parent folder"
        End If
        If Num_Detail >= 2 Then
            Files_List(2, i) = oFile.Name ' "File name"
        End If
        If Num_Detail >= 3 Then
            Files_List(3, i) = oFile.Size ' "Size"
        End If
        If Num_Detail >= 4 Then
            Files_List(4, i) = oFile.DateLastModified ' "Date last modified"
        End If
        If Num_Detail >= 5 Then
            Files_List(5, i) = oFile.DateCreated ' "Date created"
        End If
        If Num_Detail >= 6 Then
            Files_List(6, i) = oFile.DateLastAccessed ' "Date last accessed"
        End If
        If Num_Detail >= 7 Then
            Files_List(7, i) = oFile.Type ' "Type"
        End If
        If Num_Detail >= 8 Then
            Files_List(8, i) = oFile.Attributes ' "Attributes"
        End If
        If Num_Detail >= 9 Then
            Files_List(9, i) = oFile.ShortPath ' "Short path"
        End If
        If Num_Detail >= 10 Then
            Files_List(10, i) = oFile.ShortName ' "Short name"
        End If
     
        If i Mod 100 = 0 Then
            Application.StatusBar = "Get files list : " & i & " files had been listed."
        End If
    Next oFile
     
    For Each oSubFolder In oSourceFolder.SubFolders
        ' Any specific treatment for folders
    Next oSubFolder
     
    If bIncludeSubfolders Then
        For Each oSubFolder In oSourceFolder.SubFolders
            Call ListFilesInFolder(oSubFolder.Path, True, False, Num_Detail, Files_List)
        Next oSubFolder
    End If
     
    ' Resetting the progress bar
    If bUpperCall Then
        Application.StatusBar = False
    End If
     
    Exit Sub      ' Exit to avoid handler.
    ErrorHandler: ' Error-handling routine.
        i = i + 1
        ReDim Preserve Files_List(1 To Num_Detail, 1 To i)
        Files_List(1, i) = "####ERROR IN READING Folder: " & strFolderName & vbNewLine & "Erreur: " & Err.Number & vbNewLine & Err.Description
     
    End Sub

  6. #6
    Nouveau candidat au Club
    Homme Profil pro
    Consultant informatique
    Inscrit en
    Novembre 2024
    Messages
    2
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France, Hauts de Seine (Île de France)

    Informations professionnelles :
    Activité : Consultant informatique

    Informations forums :
    Inscription : Novembre 2024
    Messages : 2
    Par défaut
    Bonjour,

    J'ai fait quelques modifications dans mon programme précédent.
    1 J'ai amélioré la gestion des erreurs et complété quelques commentaires.
    2 J'ai ajouté des valeurs par défaut sur des paramètres et changé l'ordre.
    3 J'ai ajouté un paramètre pour récupérer ou non des informations sur les dossiers ou seulement les fichiers (ou fichiers et dossier vide)
    4 J'ai créé une fonction pour utiliser la procédure de façon plus directe et aussi remettre le tableaau dans le bon ordre (fichier en ligne)
    Si ça peut être utile à quelqu'un.

    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
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    Function FolderFiles(strFolderName As String, Num_Detail As Integer, Optional bFoldersDetail As Long = 0, Optional bIncludeSubfolders As Boolean = True) As Variant()
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Need to activate the reference Microsoft Scripting RunTime, to do in case of error and have ListFilesInFolder Sub Available                       '
    ' To be used this way                                                                                                                               '
    ' Dim Files() As Variant                                                                                                                            '
    ' Files = FolderFiles(Folder_To_Search, 6, 0, True) or in this case simply Files = FolderFiles(Folder_To_Search, 6)                                 '
    ' 2th parameter from 1 to 10 is the number of columns informations to get. From 1 to 6 is about same performance, from 7 it's quite slower          '
    ' 3th parameter to false if you only want to list on the folder and not it subfolders, by default to True                                           '
    ' 4th parameter to define which folders you want detailled informations, 0 => No one, 1 => Only empty Folders, 2 => All, if other same as 0(Default)'
    ' The resulting array is sorted in a kind of binary sort that may not suit you (for example Z < a < e < ê                                           '
    '                                                                                                                                                   '
    ' From Excel 2021 or Office 365 you can do Files = WorksheetFunction.Sort(FolderFiles(Folder_To_Search, 6), Array(1, 2)) to sort in a more text sort'
    ' Unfortunately it convert Date(VarType=7) to String(VarType=8) causing (if not using US Date Format) date and month inversion when pasting to excel'
    ' To avoid this Date are below converted to Double. Up to you to do later a CDate or choose date format if you paste to Excel                       '
    ' Also it convert one row array in one dimension array, to avoid this a second row is added to the result if there is only one                      '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Dim Files_List() As Variant, transpose() As Variant
    Dim B_Inf As Long, B_Sup As Long, B_Inf2 As Long, B_Sup2 As Long
    Dim i As Long, j As Long
     
    Call ListFilesInFolder(Files_List, strFolderName, Num_Detail, True, bFoldersDetail, bIncludeSubfolders)
    Application.StatusBar = False
     
    ' Transpose the resulting array to have files in lines and property in columns
    ' Slightly faster than Application.transpose and limited to 65536 lines
    B_Inf = LBound(Files_List, 1)
    B_Sup = UBound(Files_List, 1)
    B_Inf2 = LBound(Files_List, 2)
    B_Sup2 = UBound(Files_List, 2)
    If B_Inf2 = B_Sup2 Then
        ' If  there is only one row, adding a second row (Empty) to avoid WorksheetFunction.Sort generating a 1D Array
        ReDim transpose(B_Inf2 To B_Sup2 + 1, B_Inf To B_Sup)
    Else
        ReDim transpose(B_Inf2 To B_Sup2, B_Inf To B_Sup)
    End If
    ' Browse the table and copy
    For i = B_Inf To B_Sup
        For j = B_Inf2 To B_Sup2
            ' Conversion of date into Double as WorksheetFunction.Sort does not manage it correctly
            If VarType(Files_List(i, j)) = vbDate Then ' vbDate = 7
                transpose(j, i) = CDbl(Files_List(i, j))
            Else
                transpose(j, i) = Files_List(i, j)
            End If
        Next j
    Next i                                  '
    FolderFiles = transpose
     
    End Function
     
    Sub ListFilesInFolder(Files_List() As Variant, strFolderName As String, Num_Detail As Integer, bUpperCall As Boolean, Optional bFoldersDetail As Long = 0, Optional bIncludeSubfolders As Boolean = True)
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Adapted from https://www.developpez.net/forums/d200523/logiciels/microsoft-office/excel/contribuez/lister-fichiers-d-repertoire-feuille-excel/    '
    ' Need to activate the reference Microsoft Scripting RunTime, to do in case of error                                                                '
    ' To be used this way                                                                                                                               '
    ' Dim Files() As Variant                                                                                                                            '
    ' Call ListFilesInFolder(Files, Folder_To_Search, 6, True, True, 0)                                                                                 '
    ' 3th parameter from 2 to 10 is the number of columns informations to get. From 2 to 6 is about same performance, from 7 it's quite slower          '
    ' 4th parameter alway put true for the original call, false only inside this script                                                                 '
    ' 5th parameter to false if you only want to list on the folder and not it subfolders                                                               '
    ' 6th parameter to define which folders you want detailled informations, 0 => No one, 1 => Only empty Folders, 2 => All, if other same as 0         '
    ' As "ReDim Preserve" works only on last dimension the resultint array is inverted, files are in columns, informations in line                      '
    '   To get proper Array result you can apply Application.Tranpose or better (faster and avoid lines/columns limit) any Transpose function of you own'
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' Browse of the folder
    Static FSO As FileSystemObject
    Dim oSourceFolder As Scripting.Folder, oSubFolder As Scripting.Folder
    Dim oFile As Scripting.File
    Dim FolderText As String
    ' Static bNotFirstTime As Boolean defining it here was problematic when re-executing, so we pass it as a parameter
    Static i As Long
    Dim j As Long
    ' Forcing Num_Detail to 2 if lower
    If Num_Detail < 2 Then
        Num_Detail = 2
    End If
    ' If Not bNotFirstTime Then
    If bUpperCall Then
        Set FSO = CreateObject("Scripting.FileSystemObject")
        i = 0
        'bNotFirstTime = True
    End If
     
    On Error GoTo ErrorHandler
    ' Testing if no right issue to scan the folder
    If Dir(strFolderName, vbDirectory) = "" Then
        i = i + 1
        ReDim Preserve Files_List(1 To Num_Detail, 1 To i)
        If Num_Detail >= 1 Then
            Files_List(1, i) = strFolderName
        End If
        If Num_Detail >= 2 Then
           Files_List(2, i) = "####No rights to scan Folder or it does not exist: " & strFolderName
        End If
    Else ' Scanning the folder
        Set oSourceFolder = FSO.GetFolder(strFolderName)
        ' Folder treatment if bFoldersDetail = 2 or if bFoldersDetail = 1 and folder is empty (no files, no subfolders)
        If bFoldersDetail = 2 Or (bFoldersDetail = 1 And (oSourceFolder.Files.Count + oSourceFolder.SubFolders.Count) = 0) Then
            i = i + 1
            ReDim Preserve Files_List(1 To Num_Detail, 1 To i)
            If Num_Detail >= 1 Then
                j = 1
                Files_List(1, i) = oSourceFolder.Path ' "Folder path"
            End If
            If Num_Detail >= 2 Then
                j = 2
                If oSourceFolder.Files.Count + oSourceFolder.SubFolders.Count = 0 Then
                    Files_List(2, i) = "#<Empty Folder>"
                Else
                    Files_List(2, i) = "#<" & oSourceFolder.SubFolders.Count & " subfolders, " & oSourceFolder.Files.Count & " files>"
                End If
            End If
            If Num_Detail >= 3 Then
                j = 3
                Files_List(3, i) = oSourceFolder.Size ' "Size"
            End If
            If Num_Detail >= 4 Then
                j = 4
                Files_List(4, i) = oSourceFolder.DateLastModified ' "Date last modified"
            End If
            If Num_Detail >= 5 Then
                j = 5
                Files_List(5, i) = oSourceFolder.DateCreated ' "Date created"
            End If
            If Num_Detail >= 6 Then
                j = 6
                Files_List(6, i) = oSourceFolder.DateLastAccessed ' "Date last accessed"
            End If
            If Num_Detail >= 7 Then
                j = 7
                Files_List(7, i) = oSourceFolder.Type ' "Type"
            End If
            If Num_Detail >= 8 Then
                j = 8
                Files_List(8, i) = oSourceFolder.Attributes ' "Attributes"
            End If
            If Num_Detail >= 9 Then
                j = 9
                Files_List(9, i) = oSourceFolder.ShortPath ' "Short path"
            End If
            If Num_Detail >= 10 Then
                j = 10
                Files_List(10, i) = oSourceFolder.ShortName ' "Short name"
            End If
            j = 0
     
            If i Mod 100 = 0 Then
                Application.StatusBar = "Get files list : " & i & " files/folder had been listed."
            End If
        End If ' End of Folder treatment
     
        ' Files treatment
        For Each oFile In oSourceFolder.Files
            i = i + 1
            ReDim Preserve Files_List(1 To Num_Detail, 1 To i)
            'Files_List(0, i) = oFile.Path ' "Full path"
            If Num_Detail >= 1 Then
                j = 1
                Files_List(1, i) = oFile.ParentFolder.Path ' "Parent folder"
            End If
            If Num_Detail >= 2 Then
                j = 2
                Files_List(2, i) = oFile.Name ' "File name"
            End If
            If Num_Detail >= 3 Then
                j = 3
                Files_List(3, i) = oFile.Size ' "Size"
            End If
            If Num_Detail >= 4 Then
                j = 4
                Files_List(4, i) = oFile.DateLastModified ' "Date last modified"
            End If
            If Num_Detail >= 5 Then
                j = 5
                Files_List(5, i) = oFile.DateCreated ' "Date created"
            End If
            If Num_Detail >= 6 Then
                j = 6
                Files_List(6, i) = oFile.DateLastAccessed ' "Date last accessed"
            End If
            If Num_Detail >= 7 Then
                j = 7
                Files_List(7, i) = oFile.Type ' "Type"
            End If
            If Num_Detail >= 8 Then
                j = 8
                Files_List(8, i) = oFile.Attributes ' "Attributes"
            End If
            If Num_Detail >= 9 Then
                j = 9
                Files_List(9, i) = oFile.ShortPath ' "Short path"
            End If
            If Num_Detail >= 10 Then
                j = 9
                Files_List(10, i) = oFile.ShortName ' "Short name"
            End If
            j = 0
     
            If i Mod 100 = 0 Then
                Application.StatusBar = "Get files list : " & i & " files/folder had been listed."
            End If
        Next oFile
     
        If bIncludeSubfolders Then
            For Each oSubFolder In oSourceFolder.SubFolders
                Call ListFilesInFolder(Files_List, oSubFolder.Path, Num_Detail, False, bFoldersDetail, bIncludeSubfolders)
            Next oSubFolder
        End If
    End If
     
    ' Resetting the progress bar
    If bUpperCall Then
        Application.StatusBar = False
    End If
     
    Exit Sub      ' Exit to avoid handler.
    ErrorHandler: ' Error-handling routine.
        If j = 0 Then
            i = i + 1
            ReDim Preserve Files_List(1 To Num_Detail, 1 To i)
            If Num_Detail >= 1 Then
                Files_List(1, i) = strFolderName
            End If
            If Num_Detail >= 2 Then
               Files_List(2, i) = "<Impossible to scan Folder: " & strFolderName & ">"
            End If
        Else
            Files_List(j, i) = "####Erreur: " & Err.Number & " ; " & Err.Description
        End If
        Resume Next
     
    End Sub

  7. #7
    Expert confirmé
    Avatar de Qwazerty
    Homme Profil pro
    La très haute tension :D
    Inscrit en
    Avril 2002
    Messages
    4 094
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 45
    Localisation : France

    Informations professionnelles :
    Activité : La très haute tension :D
    Secteur : Service public

    Informations forums :
    Inscription : Avril 2002
    Messages : 4 094
    Par défaut
    Salut

    Je n'ai pas étudier le code et les possibilités offertes mais je met ça là, il y a peut-être des options en plus pour compléter.

    ++
    Qwaz

    MagicQwaz := Harry Potter la baguette en moins
    Le monde dans lequel on vit
    Ma page perso DVP
    Dernier et Seul Tutoriel : VBA & Internet Explorer
    Dernière contribution : Lien Tableau Structuré et UserForm
    L'utilisation de l’éditeur de message

  8. #8
    Membre expérimenté
    Homme Profil pro
    ‫‬
    Inscrit en
    Septembre 2024
    Messages
    180
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Autre

    Informations professionnelles :
    Activité : ‫‬

    Informations forums :
    Inscription : Septembre 2024
    Messages : 180
    Par défaut
    Une autre alternative sous forme d'un module de classe, ces derniers permettent de réduire considérablement la complexité du code du fait qu'il est possible d'exporter le contexte de la recherche vers le code du développeur offrant une large marge de liberté dans la sélection des fichiers selon le besoin.
    class: CSearchFiles
    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
    Option Explicit
    Public Event FileSearchNotify(ByVal aFile As Object, ByVal MatchIdx As Long, Cancel As Boolean)
    Public Event Progress(ByVal Msg As String)
     
    Function SearchFiles(ByVal aFolder As String, Optional ByVal aFilter As String, Optional Recursive As Boolean = False)
        Dim fso As Object, ObjFolder As Object
        Dim var, Actuel As Long, total As Long
        Dim Folders As New Collection
        Dim Ext As String, prog  As Long, lastProg As Long
        Dim Notify As Boolean, aCancel As Boolean
     
        If (Trim(aFilter) <> "") Then
          aFilter = IIf(InStr(aFilter, "*.*") > 0, "", ";" & UCase(aFilter) & ";")
        End If
        Set fso = CreateObject("Scripting.Filesystemobject")
        Set ObjFolder = fso.GetFolder(aFolder & "\")
        Folders.Add ObjFolder
        Do
            total = Folders.Count
            prog = Actuel * 128 \ total
            If prog <> lastProg Then
               RaiseEvent Progress(Actuel & " sur " & total & " Dossier(s)")
               lastProg = prog
            End If
            If (Actuel >= total) Or aCancel Then Exit Do
            Actuel = Actuel + 1
            Set ObjFolder = Folders(Actuel)
            On Error GoTo nNext 'Dossier inaccessible
            For Each var In ObjFolder.files
                 Notify = True
                 If aFilter <> "" Then
                    Ext = ";." & UCase(fso.GetExtensionName(var.Name)) & ";"
                    Notify = InStr(aFilter, Ext) > 0
                 End If
     
                 If Notify Then
                   SearchFiles = SearchFiles + 1
                   RaiseEvent FileSearchNotify(var, SearchFiles, aCancel)
                   If aCancel Then Exit Do
                 End If
            Next
            If Not Recursive Then Exit Do
            For Each var In ObjFolder.SubFolders
               Folders.Add var
            Next
    nNext: If Err.Number <> 0 Then
              Err.Clear
           End If
        Loop
        Set Folders = Nothing
    End Function
    Utilisation:
    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
     
    Dim WithEvents Browser As CSearchFiles
     
    Private Sub Browser_FileSearchNotify(ByVal aFile As Object, ByVal MatchIdx As Long, Cancel As Boolean)
        Cells(MatchIdx, 1) = aFile.ParentFolder.Path
        Cells(MatchIdx, 2) = aFile.Path
        Cells(MatchIdx, 3) = aFile.Name
        Cells(MatchIdx, 4) = aFile.Size
        Cells(MatchIdx, 5) = aFile.Type
        Cells(MatchIdx, 6) = aFile.DateCreated
        Cells(MatchIdx, 7) = aFile.DateLastModified
        Cells(MatchIdx, 8) = aFile.DateLastAccessed
        Cells(MatchIdx, 9) = aFile.Attributes
        Cells(MatchIdx, 10) = aFile.ShortPath
        Cells(MatchIdx, 11) = aFile.ShortName
    End Sub
     
    Private Sub Browser_Progress(ByVal Msg As String)
      Caption = Msg
      DoEvents
    End Sub
     
    Private Sub BSearch_Click()
     Set Browser = New CSearchFiles
     Application.ScreenUpdating = False
     Browser.SearchFiles DossierEdit, FilterEdit, Recursive.Value
     Application.ScreenUpdating = True
    End Sub
     
    Private Sub BSelectDir_Click()
      With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show <> 0 Then
           DossierEdit.Text = .SelectedItems(1)
        End If
      End With
    End Sub
    J’espère que cela fonctionne pour tout le monde.
    Fichiers attachés Fichiers attachés

Discussions similaires

  1. Réponses: 5
    Dernier message: 30/08/2013, 09h06
  2. Lister les fichiers d'un répertoire dans une listebox
    Par soshelpvb dans le forum VB.NET
    Réponses: 8
    Dernier message: 05/11/2012, 11h57
  3. Réponses: 9
    Dernier message: 05/01/2012, 19h27
  4. Lister les fichiers d'un répertoire dans une feuille Excel
    Par Kriss63 dans le forum Macros et VBA Excel
    Réponses: 1
    Dernier message: 21/04/2011, 14h54
  5. lister les fichiers d'un répertoire dans un .BAT
    Par isn44 dans le forum Windows
    Réponses: 7
    Dernier message: 10/10/2007, 10h44

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