Example 8: Use the concept of the above two examples and write a VBA code that enlists all the files inside a current location and its subfolder.
For this example you can use the following code:
- Sub Retrieve_File_listing()
- Worksheets(1).Cells(2, 1).Activate
- Call Enlist_Directories("C:\Users\Ankit\Desktop\ExcelTrick\ ", 1)
- End Sub
- Public Sub Enlist_Directories(strPath As String, lngSheet As Long)
- Dim strFldrList() As String
- Dim lngArrayMax, x As Long
- lngArrayMax = 0
- strFn = Dir(strPath & "*.*", 23)
- While strFn <> ""
- If strFn <> "." And strFn <> ".." Then
- If (GetAttr(strPath & strFn) And vbDirectory) = vbDirectory Then
- lngArrayMax = lngArrayMax + 1
- ReDim Preserve strFldrList(lngArrayMax)
- strFldrList(lngArrayMax) = strPath & strFn & "\"
- Else
- ActiveCell.Value = strPath & strFn
- Worksheets(lngSheet).Cells(ActiveCell.Row + 1, 1).Activate
- End If
- End If
- strFn = Dir()
- Wend
- If lngArrayMax <> 0 Then
- For x = 1 To lngArrayMax
- Call Enlist_Directories(strFldrList(x), lngSheet)
- Next
- End If
- End Sub
Explanation: This code first iterates through all the folders present inside a location and stores them in an array. Later it recursively calls the ‘
Enlist_Directories
’ function to retrieve the file names.
So, this was all about VBA DIR Function in Excel.
No comments:
Post a Comment