I think that should do the trick.
This macro will take folder path from cell A1
and list recursively its contents and subfolder contents with hyperlinks.
Update: fixed, now it’s working. 🙂
Public Position As Integer
Public Indent As Integer
Sub ListFileTree()
Position = 0
Indent = 0
Call RecurseFolderList(Range("A1").Value)
End Sub
Private Sub ClearFormatting(Rng As Range)
Rng.Formula = Rng.Value2
Rng.Font.ColorIndex = xlAutomatic
Rng.Font.Underline = xlUnderlineStyleNone
End Sub
Function GetFilenameFromPath(ByVal strPath As String) As String
If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
GetFilenameFromPath = GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
End If
End Function
Function RecurseFolderList(FolderName As String) As Boolean
On Error Resume Next
Dim FSO, NextFolder, FolderArray, FileArray, NextFile
Dim OriginalRange As Range
Dim RemoveHyperlink As Boolean
Set FSO = CreateObject("Scripting.FileSystemObject")
If Err.Number > 0 Then
RecurseFolderList = False
Exit Function
End If
On Error GoTo 0
If FSO.FolderExists(FolderName) Then
Set NextFolder = FSO.GetFolder(FolderName)
Set FolderArray = NextFolder.SubFolders
Set FileArray = NextFolder.Files
RemoveHyperlink = False
Set OriginalRange = Range("A2").Offset(Position - 1, Indent)
Indent = Indent + 1
For Each NextFolder In FolderArray
Range("A2").Offset(Position, Indent).Formula = "=HYPERLINK(""" & NextFile & """,""" & UCase(GetFilenameFromPath(NextFolder)) & """)"
Position = Position + 1
RecurseFolderList (NextFolder)
RemoveHyperlink = True
Next
For Each NextFile In FileArray
Range("A2").Offset(Position, Indent).Formula = "=HYPERLINK(""" & NextFile & """,""" & GetFilenameFromPath(NextFile) & """)"
Position = Position + 1
RemoveHyperlink = False
DoEvents
Next
If RemoveHyperlink Then
Call ClearFormatting(OriginalRange)
End If
Set NextFolder = Nothing
Set FolderArray = Nothing
Set FileArray = Nothing
Set NextFile = Nothing
Else
RecurseFolderList = False
End If
Set FSO = Nothing
Indent = Indent - 1
End Function
solved Make folders and files using excel vba macro and display with tree view and hyperlinks