I have the following code below, but get permission denied when running the code.
See full code below
It would be appreciated if someone could amend my code
Code:
For Each subFolder In folder.Subfolders
See full code below
Code:
Sub ExtractSubFolderNames()
Dim folderPath As String
Dim fso As Object
Dim outputRow As Integer
Dim excludedFolders As Variant
Dim folder As Object
' Set the folder path to the root of the C: drive
folderPath = "C:\" ' Root directory of the C: drive
' List of folders to exclude
excludedFolders = Array("Data", "Users", "Program Data", "Program Files", "RECYCLE")
' Initialize FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
' Start output from row 1 on the "Subfolders" sheet
outputRow = 1
' Attempt to get the folder and handle permission denied
On Error GoTo PermissionDeniedHandler
Set folder = fso.GetFolder(folderPath)
On Error GoTo 0 ' Reset error handling
' Call the recursive function to list all subfolders
Call ListSubFolders(folder, excludedFolders, outputRow)
MsgBox "Subfolders extraction complete."
Exit Sub
PermissionDeniedHandler:
MsgBox "Permission denied when accessing: " & folderPath
Resume Next ' Skip this folder and continue with the next one
End Sub
' Recursive function to list all subfolders
Sub ListSubFolders(ByVal folder As Object, ByVal excludedFolders As Variant, ByRef outputRow As Integer)
Dim subFolder As Object
Dim subFolderPath As String
' Loop through each subfolder
For Each subFolder In folder.Subfolders
subFolderPath = subFolder.Path
' Check if the subfolder is not in the excluded list
If IsError(Application.Match(subFolder.Name, excludedFolders, 0)) Then
' If not excluded, output the folder path (subfolder) in column A on the "Subfolders" sheet
ThisWorkbook.Sheets("Subfolders").Cells(outputRow, 1).Value = subFolderPath
outputRow = outputRow + 1
End If
' Recursively call the function to find sub-subfolders
Call ListSubFolders(subFolder, excludedFolders, outputRow)
Next subFolder
End Sub
It would be appreciated if someone could amend my code