Folders
To create a sheet with the Folder name and fill in column A, use the following code, where the explanation is commented in the code:
Option Explicit
Sub Listar_Pastas()
''''''''''''''''''''
'==== Pastas ===='
''''''''''''''''''''
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim xPath As String, xDir As String
Dim xWs_pastas As Worksheet
Dim fso As Object
Dim fso_FOLDER As Object
Dim fso_folders As Object
Dim i As Long
Set fso = CreateObject("Scripting.FileSystemObject")
'Janela para escolher a pasta do diretório desejado
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Escolha a pasta"
.Show
End With
On Error Resume Next
xPath = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & "\"
If xPath = "" Then
GoTo CleanExit 'Se o caminho da pasta não existir
End If
'Define novo Objeto FSO GetFolder
Set fso_FOLDER = fso.GetFolder(xPath)
xDir = fso_FOLDER.Name
'Apaga se houver planilha com mesmo nome existente
CriarPlanilha (xDir)
'Define nova planilha da pasta
Set xWs_pastas = ThisWorkbook.Sheets(xDir)
'https://stackoverflow.com/a/31428399/7690982
'Encontra todos os Arquivos
i = 1
If fso_FOLDER.subFolders.Count > 0 Then
'Loop em cada pasta do diretório escolhido
For Each fso_folders In fso_FOLDER.subFolders
With xWs_pastas
'Preenche a coluna A com a lista de arquivos
.Cells(i, "A") = fso_folders.Name
End With
i = i + 1
Next fso_folders
Else
MsgBox "Nenhuma pasta encontrada em " & xPath
GoTo CleanExit
End If
'Sair do código
CleanExit:
Set fso = Nothing
Set fso_FOLDER = Nothing
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
If Err.Number <> 0 Then MsgBox "Ocorreu um erro em: " & Err.Number & " " & Err.Description
End Sub
Public Function CriarPlanilha(Name As String)
Dim s As Worksheet, t As String
Dim i As Long, k As Long
Dim t_exists As Boolean
k = ThisWorkbook.Sheets.Count
t_exists = False
'Verifica em todas as planilhas se o nome já existe
For i = k To 1 Step -1
t = ThisWorkbook.Sheets(i).Name
If t = Name Then
'Se existir, limpa o conteúdo
t_exists = True
Application.DisplayAlerts = False
ThisWorkbook.Sheets(i).UsedRange.ClearContents
Application.DisplayAlerts = True
End If
Next i
'Se não existir, cria nova planilha
If t_exists = False Then
ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(k)).Name = Name
End If
End Function
Subfolders and more data
If you also want the subdirectories and other directory data, use the following code:
Option Explicit
Sub Listar_Subdir()
''''''''''''''''''''
'==== Subdir ===='
''''''''''''''''''''
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
Dim xDir As String, xDirName As String
Dim xWs As Worksheet
Dim ncell As Long
Dim vaArray As Variant
Dim i As Long, j As Long
Dim folder As Object, fso As Object
'https://www.extendoffice.com/documents/excel/2994-excel-list-all-files-in-folder-and-subfolders.html
'Updateby20150706
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
Set fso = CreateObject("Scripting.FileSystemObject")
'Escolher a pasta desejada
With folder
.Title = "Escolha a pasta"
End With
If folder.Show <> -1 Then GoTo CleanExit
On Error Resume Next
xDir = folder.SelectedItems(1) & "\"
xDirName = fso.GetFolder(xDir).Name
'Cria a planilha com o nome do Diretório
SheetKiller (xDirName)
ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(Sheets.Count)).Name = xDirName
Set xWs = ThisWorkbook.Sheets(xDirName)
'Cria a Lista de Subdiretórios na planilha xWs
ListFilesInFolder xDir, True, xWs
'Sair do código
CleanExit:
Set fso = Nothing
Set folder = Nothing
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
If Err.Number <> 0 Then MsgBox "Ocorreu um erro em: " & Err.Number & " " & Err.Description
End Sub
Public Sub ListFilesInFolder(ByVal xFolderName As String, ByVal xIsSubfolders As Boolean, xWs As Worksheet)
Dim xFileSystemObject As Object
Dim xFolder As Object
Dim xSubFolder As Object
Dim xFolderChild As Object
Dim rowIndex As Long
Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
Set xFolder = xFileSystemObject.GetFolder(xFolderName)
rowIndex = xWs.Range("A" & xWs.Rows.Count).End(xlUp).Row + 1
For Each xSubFolder In xFolder.SubFolders
With xWs
.Cells(rowIndex, 1) = xSubFolder.Path
.Cells(rowIndex, 2) = xSubFolder.Name
.Cells(rowIndex, 3) = xSubFolder.Size
.Cells(rowIndex, 4) = xSubFolder.ShortName
.Cells(rowIndex, 5) = xSubFolder.ShortPath
.Cells(rowIndex, 6) = xSubFolder.DateCreated
.Cells(rowIndex, 7) = xSubFolder.DateLastAccessed
.Cells(rowIndex, 8) = xSubFolder.DateLastModified
End With
rowIndex = rowIndex + 1
Next xSubFolder
If xIsSubfolders Then
For Each xFolderChild In xFolder.SubFolders
ListFilesInFolder xFolderChild.Path, True, xWs
Next xFolderChild
End If
Set xSubFolder = Nothing
Set xFolder = Nothing
Set xFileSystemObject = Nothing
End Sub
Public Function SheetKiller(Name As String)
Dim s As Worksheet, t As String
Dim i As Long, k As Long
k = ThisWorkbook.Sheets.Count
For i = k To 1 Step -1
t = ThisWorkbook.Sheets(i).Name
If t = Name Then
Application.DisplayAlerts = False
ThisWorkbook.Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
End Function
I’d like to know how I get him to start listing from the A2 line, I’d like to put the titles to identify in the first line. I recorded a macro for him to create a spreadsheet with this data and make it cute, but you have to define where it starts and where it ends and I wanted him to create the spreadsheet only as far as it contains text
– Paulo Cordeiro
@In the first code, change
i = 1
fori = 2
, already in the second you need either add the title by the code on line 1 or create a conditionalif
, to check if you have nothing filled, skip to the second line.– danieltakeshi
Thank you very much guy helped me a lot, after these experiences I had with some VBA programs I’m even thinking about attending something related to the area when I finish high school
– Paulo Cordeiro
Sorry to come back here again, but I had to change some things in the spreadsheet and now I can’t make it work, I would like to change the initial idea of deleting the spreadsheet if it already exists to clean all of it (except the G1 cell), after selecting it and listing normally, I was able to change the Sheetkiller function to clean but I can’t make it work from there because always appears a different error, I imagine you have to take the Sheet.Add part and switch to some code that just takes you to the chosen sheet
– Paulo Cordeiro
This all pq when the spreadsheet is deleted spoils a dynamic table that pulls a data from the G1 line, even if it is being created again with the same name does not work, so if there is a way to keep it, the original code can remain as well
– Paulo Cordeiro
@Paulocorder See the Edit.
– danieltakeshi