2017年11月16日星期四

Excel VBA - Scan Files in Folder

Const TopLevelFolder = "C:\Users\Administrator\Dropbox\CCBA\Data Extraction\asihkdmsq11-SSIS-20171108-masked\asihkdmsq11-SSIS-20171108-masked"

'Creating a FileSystemObject
Public FSO As New FileSystemObject

Sub MAIN()

    ' Clear Data
    Sheets(1).Select
    Cells(1, 1).CurrentRegion.Select
    Selection.Delete
    
    ' Create Header
    sHeader = "No|File Path|File Name|File Type|File Size(M)|Modification Date"
    aHeader = Split(sHeader, "|")
    
    For c = 0 To UBound(aHeader)
        Cells(1, c + 1).Value = aHeader(c)
    Next c
    
    Cells(2, 1).Select
    
    ' Scan Folder
    ScanFolder (TopLevelFolder)
    
    ' Post-Actions
    LastRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row
    
    Cells(2, 1).Value = 1
    Cells(3, 1).Value = 2
    
    Range("A2:A3").Select
    Selection.AutoFill Destination:=Range("A2:A" & LastRow)
        
    Columns("E:E").Select
    Selection.NumberFormat = "0.0"
    
    Columns.AutoFit
    Cells(1, 1).Select
End Sub

Sub ScanFolder(sFolder As Variant)
    'Declaring variables
    Dim objFolder As Folder
    Dim objFile As file
    Dim objSubFolder As Folder
    ' Dim strPath As String
    Dim NextRow As Long
    
    'Create the object of this folder
    Set objFolder = FSO.GetFolder(sFolder)
    
    'Find the next available row
    NextRow = ActiveSheet.Cells(Rows.Count, "B").End(xlUp).Row + 1

    'Loop through each file in the folder
    For Each objFile In objFolder.Files
        If InStr(objFile.Name, "dtsx") > 0 Then
            'List the name, size, and date/time of the current file
            Cells(NextRow, 2).Value = Replace(objFile.Path, objFile.Name, "")
            Cells(NextRow, 3).Value = objFile.Name
            Cells(NextRow, 4).Value = objFile.Type
            Cells(NextRow, 5).Value = objFile.Size / 1025 / 1025
            Cells(NextRow, 6).Value = objFile.DateLastModified
            'Find the next row
            NextRow = NextRow + 1
        End If
    Next objFile

    For Each objSubFolder In objFolder.SubFolders
        ScanFolder (objSubFolder.Path)
    Next objSubFolder
End Sub

沒有留言:

發佈留言