Les galetes ens ajuden a lliurar els nostres serveis. En utilitzar els nostres serveis, accepteu el nostre ús de cookies.
Consell: altres idiomes es tradueixen en Google. Pots visitar el English versió d'aquest enllaç.
Iniciar Sessió
x
or
x
x
Registre
x

or

Com es mostren totes les carpetes i subcarpetes d'Excel?

Alguna vegada has patit aquest problema que llista totes les carpetes i subcarpetes d'un directori especificat en un full de càlcul? En Excel, no hi ha cap manera ràpida i pràctica d'obtenir el nom de totes les carpetes d'un directori específic alhora. Per fer front a la tasca, aquest article us pot ajudar.

Llista totes les carpetes i subcarpetes amb codi VBA


fletxa blau dreta bombolla Llista totes les carpetes i subcarpetes amb codi VBA


Si voleu obtenir tots els noms de carpetes d'un directori determinat, el següent codi VBA us pot ajudar, feu el següent:

1. Mantingueu premut el botó ALT + F11 tecles i obre el Finestra de Microsoft Visual Basic per a aplicacions.

2. Clic Insereix > Mòduls, i enganxeu el següent codi al Finestra de mòduls.

Codi VBA: llista totes les carpetes i noms de subcarpeta

Sub FolderNames()
'Update 20141027
Application.ScreenUpdating = False
Dim xPath As String
Dim xWs As Worksheet
Dim fso As Object, j As Long, folder1 As Object
With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Choose the folder"
    .Show
End With
On Error Resume Next
xPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"
Application.Workbooks.Add
Set xWs = Application.ActiveSheet
xWs.Cells(1, 1).Value = xPath
xWs.Cells(2, 1).Resize(1, 5).Value = Array("Path", "Dir", "Name", "Date Created", "Date Last Modified")
Set fso = CreateObject("Scripting.FileSystemObject")
Set folder1 = fso.getFolder(xPath)
getSubFolder folder1
xWs.Cells(2, 1).Resize(1, 5).Interior.Color = 65535
xWs.Cells(2, 1).Resize(1, 5).EntireColumn.AutoFit
Application.ScreenUpdating = True
End Sub
Sub getSubFolder(ByRef prntfld As Object)
Dim SubFolder As Object
Dim subfld As Object
Dim xRow As Long
For Each SubFolder In prntfld.SubFolders
    xRow = Range("A1").End(xlDown).Row + 1
    Cells(xRow, 1).Resize(1, 5).Value = Array(SubFolder.Path, Left(SubFolder.Path, InStrRev(SubFolder.Path, "\")), SubFolder.Name, SubFolder.DateCreated, SubFolder.DateLastModified)
Next SubFolder
For Each subfld In prntfld.SubFolders
    getSubFolder subfld
Next subfld
End Sub

3. A continuació, premeu F5 clau per executar aquest codi i a Tria la carpeta apareixerà la finestra, llavors heu de seleccionar el directori que voleu que es mostri la carpeta i els noms de les subcarpetes, vegeu la captura de pantalla:

doc-list-folder-names-1

4. Clic OK, i obtindreu la ruta, el directori, el nom, la data creada i la darrera data modificada de la carpeta i subcarpetes en un llibre nou, vegeu la captura de pantalla:

doc-list-folder-names-1


Article relacionat:

Com es listen els fitxers d'un directori al full de càlcul d'Excel?



Eines de productivitat recomanades

Pestanya d'Office

estrella d'or1 Porteu les pestanyes pràctiques a l'Excel i a un altre programari d'Office, igual que Chrome, Firefox i el nou Internet Explorer.

Kutools for Excel

estrella d'or1 Increïble! Incrementeu la productivitat en 5 minuts. No necessites cap habilitat especial, estalvieu dues hores cada dia.

estrella d'or1 300 Noves característiques per a Excel, Excel molt fàcil i potent:

  • Combina cel·les / files / columnes sense perdre dades.
  • Combina i consolida diverses fulles i llibres.
  • Comparar intervals, copiar diversos rangs, convertir text a data, unitat i conversió de divises.
  • Compte per colors, subtotals de paginació, classificació avançada i filtre súper,
  • Més Seleccioneu / Insereix / Suprimeix / Text / Format / Enllaç / Comentari / Llibres / Eines de full de càlcul ...

Tret de pantalla de Kutools per a Excel

Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    lloyd · 3 months ago
    Hello. Can you please please help me on a code which I am struggling to find.

    Below are the requirements for the code.



    1. The VBA should go through all the folders and sub-folders
    and check each and every type of file. The user should only give the path for
    the top folder. The code should then check all the folders and sub folders
    within the top folder.



    2. After checking the files, the code should zip all files
    which have not been accessed for more than 3 months. The accessed period is
    something which I should be able to change in future if required. It should
    allow me to change it to 1 month or 5 months if required.



    3. After zipping the files, the code should delete the
    original files which were zipped.



    4. The zipped file should be saved in the same path as the
    original file.
  • To post as a guest, your comment is unpublished.
    tom vincent · 1 years ago
    I modified it to add size:



    Sub FolderNames()
    'Update 20141027
    Application.ScreenUpdating = False
    Dim xPath As String
    Dim xWs As Worksheet
    Dim fso As Object, j As Long, folder1 As Object
    With Application.FileDialog(msoFileDialogFolderPicker)
    .Title = "Choose the folder"
    .Show
    End With
    On Error Resume Next
    xPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"
    Application.Workbooks.Add
    Set xWs = Application.ActiveSheet
    xWs.Cells(1, 1).Value = xPath
    xWs.Cells(2, 1).Resize(1, 6).Value = Array("Path", "Dir", "Name", "Date Created", "Date Last Modified","Size")
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder1 = fso.getFolder(xPath)
    getSubFolder folder1
    xWs.Cells(2, 1).Resize(1, 6).Interior.Color = 65535
    xWs.Cells(2, 1).Resize(1, 6).EntireColumn.AutoFit
    Application.ScreenUpdating = True
    End Sub
    Sub getSubFolder(ByRef prntfld As Object)
    Dim SubFolder As Object
    Dim subfld As Object
    Dim xRow As Long
    For Each SubFolder In prntfld.SubFolders
    xRow = Range("A1").End(xlDown).Row + 1
    Cells(xRow, 1).Resize(1, 6).Value = Array(SubFolder.Path, Left(SubFolder.Path, InStrRev(SubFolder.Path, "\")), SubFolder.Name, SubFolder.DateCreated, SubFolder.DateLastModified, SubFolder.Size)
    Next SubFolder
    For Each subfld In prntfld.SubFolders
    getSubFolder subfld
    Next subfld
    End Sub
    • To post as a guest, your comment is unpublished.
      AL · 1 years ago
      When you include the SubFolder.Size function the script no longer list all the subfolders, only the first level.
      How can I include the size and get all subfolders listed?
  • To post as a guest, your comment is unpublished.
    jimbosmiles · 1 years ago
    I am with the others - it works up to a point.

    For me, that point is it creates the new s/s, details the folder I have shown (in Cells A1), the a yellow highlighted bar in row 2 with the headings followed by nothing else!

    The folder I am looking at is empty except for sub folders (i.e. no data files exist) and the sub folders do not appera at all.

    Can anyone help me list the sub folders and their files?
  • To post as a guest, your comment is unpublished.
    Paul J · 1 years ago
    When I run this code it works but it only shows the first folder in side the folder that I choose. For example,

    When I run the code I choose "C:\Users\Johnson\Music" (Note: I have 70 Folders inside my Music Folder)

    When the code runs it only shows the first folder and then list all the folders inside that folder.

    I would like it to list all the folders inside the Music folder.
  • To post as a guest, your comment is unpublished.
    Caralyn · 1 years ago
    Hello,
    I just followed your directions but I'm getting errors when I hit F5 to run. The error below highlights "Dim xWs As Worksheet". Is there an updated code I can use?
    Compile error:
    User-defined type not defined
    • To post as a guest, your comment is unpublished.
      Robert Poole · 1 years ago
      [quote name="Caralyn"]Hello,
      I just followed your directions but I'm getting errors when I hit F5 to run. The error below highlights "Dim xWs As Worksheet". Is there an updated code I can use?
      Compile error:
      User-defined type not defined[/quote]

      Are you using the Kutools add-on or MS Excel VBA editor? Since I am not using the add-on, I am unable to duplicate your error. Using MS VBA Editor works without any errors.