Last active
          February 15, 2023 02:30 
        
      - 
      
- 
        Save thoriqmacto/40513f6d092f59815984fe8a0a0a39a2 to your computer and use it in GitHub Desktop. 
    List all files inside the folder using VBA. Select cell containing full address of folder that want files to be listed
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | Sub ListFiles() | |
| 'Set a reference to Microsoft Scripting Runtime by using | |
| 'Tools > References in the Visual Basic Editor (Alt+F11) | |
| 'Declare the variables | |
| Dim objFSO As Object | |
| Dim objTopFolder As Object | |
| Dim strTopFolderName As String | |
| Dim flink As Range | |
| Set flink = Range("R2") | |
| 'Assign the top folder to a variable | |
| strTopFolderName = flink.Value | |
| 'Insert the headers for Columns A through F | |
| Range("A1").Value = "File Name" | |
| Range("B1").Value = "File Size" | |
| Range("C1").Value = "File Type" | |
| Range("D1").Value = "Date Created" | |
| Range("E1").Value = "Date Last Accessed" | |
| Range("F1").Value = "Date Last Modified" | |
| 'Create an instance of the FileSystemObject | |
| Set objFSO = CreateObject("Scripting.FileSystemObject") | |
| 'Get the top folder | |
| Set objTopFolder = objFSO.GetFolder(strTopFolderName) | |
| 'Call the RecursiveFolder routine | |
| Call RecursiveFolder(objTopFolder, True) | |
| 'Change the width of the columns to achieve the best fit | |
| Columns.AutoFit | |
| End Sub | |
| Sub RecursiveFolder(objFolder As Object, IncludeSubFolders As Boolean) | |
| 'Declare the variables | |
| Dim objFile As Object | |
| Dim objSubFolder As Object | |
| Dim NextRow As Long | |
| 'Find the next available row | |
| NextRow = Cells(Rows.Count, "A").End(xlUp).Row + 1 | |
| 'Loop through each file in the folder | |
| For Each objFile In objFolder.Files | |
| Cells(NextRow, "A").Value = objFile.Name | |
| Cells(NextRow, "B").Value = objFile.Size | |
| Cells(NextRow, "C").Value = objFile.Type | |
| Cells(NextRow, "D").Value = objFile.DateCreated | |
| Cells(NextRow, "E").Value = objFile.DateLastAccessed | |
| Cells(NextRow, "F").Value = objFile.DateLastModified | |
| NextRow = NextRow + 1 | |
| Next objFile | |
| 'Loop through files in the subfolders | |
| If IncludeSubFolders Then | |
| For Each objSubFolder In objFolder.SubFolders | |
| Call RecursiveFolder(objSubFolder, True) | |
| Next objSubFolder | |
| End If | |
| End Sub | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Life saver! Thank you for your support!