Sunday, April 2, 2017

File System Object

Sub GetFileStructure()
    Dim fileNames1() As String
    Dim path1 As String
   
    If Trim(Range("G3").value = "") Or Trim(Range("G4").value = "") Then
        MsgBox "Please enter correct path and type to proceed!"
    Else
        path1 = Range("G3").value
 
        Select Case Range("G4").value
            Case "File"
                fileNames1() = GetAllFiles(path1)
            Case "Folder"
                fileNames1() = GetAllFolders(path1)
        End Select
   
        Call ClearRows  'delete last search
        For i = 0 To UBound(fileNames1()) Step 1
            'MsgBox fileNames1(i)
            Cells(10 + i, 1).value = fileNames1(i)
        Next
    End If
End Sub

Function GetAllFiles(path1 As String)
    Dim fso As New FileSystemObject
    Dim folder1 As Folder
    Dim file1 As File
    Dim fileNames1() As String
    Dim i As Integer

    ReDim fileNames1(0) As String
    If fso.FolderExists(path1) Then
        Set folder1 = fso.GetFolder(path1)
   
        For Each file1 In folder1.Files
            i = IIf(fileNames1(0) = "", 0, i + 1)
            ReDim Preserve fileNames1(i) As String
            fileNames1(i) = file1.Name
            'Debug.Print file1.Name
        Next
    End If
   
    GetAllFiles = fileNames1
End Function

Function GetAllFolders(path1 As String)
    Dim fso As New FileSystemObject
    Dim folder1 As Folder
    Dim subFolder1 As Folder
    'Dim file1 As File
    Dim folderNames1() As String
    Dim i As Integer

    ReDim folderNames1(0) As String
    If fso.FolderExists(path1) Then
        Set folder1 = fso.GetFolder(path1)

        For Each subFolder1 In folder1.SubFolders
            i = IIf(folderNames1(0) = "", 0, i + 1)
            ReDim Preserve folderNames1(i) As String
            folderNames1(i) = subFolder1.Name
            'Debug.Print subFolder1.Name
        Next
    End If

    'MsgBox folder1.Path
    GetAllFolders = folderNames1
End Function

Sub ClearRows()
    Dim rowCount As Integer
   
    rowCount = ActiveSheet.UsedRange.Rows.Count + 1
    'MsgBox rowCount
    Range("A10", Cells(rowCount, 1)).value = ""
End Sub

No comments:

Post a Comment

*INTERVIEW QUESTIONS

* Ques 01. What is the difference between ByVal and ByRef and which is default ? Ans-  ByRef : If you pass an argument by reference when...