Guest User

Untitled

a guest
May 14th, 2018
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Private fileCounter As Integer
  2. Private activeSht As Worksheet
  3. 'Display all the files in a folder. Searches all the sub folders.
  4.  
  5. 'Prints Folder Names in Column A and and the file Names in Column B
  6.  
  7. Sub SearchFiles()
  8.     Dim pth As String
  9.     Dim fso As FileSystemObject
  10.     Dim baseFolder As Folder
  11.                    
  12. '    pth = "C:\hadoop\data\RefUSADownloads" 'the base path which has to be searched for Files
  13.     pth = "C:\hadoop\data\prospectsTest" 'the base path which has to be searched for Files
  14.  
  15.     Set fso = New FileSystemObject
  16.                    
  17.     ''check if the folder actually exists or not
  18.                    
  19.     If (Not (fso.FolderExists(pth))) Then
  20.         'the folder path is invalid. Exiting.
  21.         MsgBox "Invalid Path"
  22.         Exit Sub
  23.     End If
  24.    
  25.     Set baseFolder = fso.GetFolder(pth)
  26.    
  27.     fileCounter = 1
  28.     Set activeSht = ActiveSheet
  29.    
  30.     activeSht.Range("A1").Value = "Folder Name"
  31.     activeSht.Range("B1").Value = "File Name"
  32.    
  33.     On Error GoTo ErrHandler
  34.     Application.ScreenUpdating = False
  35.     Application.Calculation = xlCalculationManual
  36.     PrintFileNames baseFolder
  37.    
  38. ErrHandler:
  39.     Application.ScreenUpdating = True
  40.     Application.Calculation = xlCalculationAutomatic
  41. End Sub
  42.    
  43.    
  44. Sub PrintFileNames(baseFolder As Folder)
  45.     Dim folder_ As Folder
  46.     Dim file_ As File
  47.     Dim xlWB As Excel.Workbook
  48.    
  49.     For Each folder_ In baseFolder.SubFolders
  50.         'call recursive function.
  51.         PrintFileNames folder_
  52.     Next folder_
  53.    
  54.     For Each file_ In baseFolder.Files
  55.         'print files here
  56.         activeSht.Range("A1").Offset(fileCounter, 0).Value = baseFolder.Path
  57.         activeSht.Range("B1").Offset(fileCounter, 0).Value = file_.Name
  58.         activeSht.Range("C1").Offset(fileCounter, 0).Value = file_.Type
  59.         Set xlWB = xlApp.Workbooks.Open(file_.Path & file_.Name)
  60. '        xlWB.SaveAs
  61.         fileCounter = fileCounter + 1
  62.     Next file_
  63. End Sub
Add Comment
Please, Sign In to add comment