엑셀 팁

Excel VBA를 활용한 폴더 내 모든 파일의 이름과 경로 추출 방법 - 하이퍼링크 포함

아무개a 2023. 2. 22. 23:03
반응형

VBA 활용해서 특정 폴더 내 파일 이름을 추출하는 것과

모든 워크시트의 이름을 추출하는 VBA 코드를 블로그에 올렸다.

 

하는 김에 선택된 폴더 내 모든 하위 폴더를 스캔해서 모든 파일명을 조사한 뒤에

그파일명과 경로까지 엑셀에 리스트 업 해주는 코드를 만들었다(사실 GPT한테 만들어달라고 했다)

 

Sub ListFilesInFolder()
 
    Dim FolderPath As String
    Dim FileName As String
    Dim i As Integer
    Dim j As Integer
    
    ' Get the folder path
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        If .Show = -1 Then
            FolderPath = .SelectedItems(1) & "\"
        End If
    End With
    
    If FolderPath = "" Then Exit Sub ' User cancelled, so exit
    
    ' Delete existing "File List" sheet if it exists
    On Error Resume Next
    Application.DisplayAlerts = False
    Worksheets("File List").Delete
    Application.DisplayAlerts = True
    On Error GoTo 0
    
    ' Create a new "File List" sheet
    Sheets.Add(After:=ActiveSheet).Name = "File List"
    Range("A1").Value = "Path"
    Range("B1").Value = "Filename"
    
    ' Recursively loop through all subfolders and files in the selected folder
    i = 2 ' Start at row 2, since row 1 has headers
    ListFilesInFolderRecursive FolderPath, i
    
    ' Add hyperlinks to paths in column A
    For j = 2 To i - 1
        Worksheets("File List").Hyperlinks.Add Anchor:=Range("A" & j), Address:=Range("A" & j).Value, TextToDisplay:=Range("A" & j).Value
    Next j
    
    ' Store the time the macro was run in cell C1
    Range("C1").Value = Now()
 
End Sub
 
 
Sub ListFilesInFolderRecursive(ByVal FolderPath As String, ByRef i As Integer)
 
    Dim FileName As String
    Dim SubFolderPath As String
    Dim SubFolder As Folder
    Dim FileItem As File
    Dim fso As New FileSystemObject ' FileSystemObject 객체 초기화
    
    ' Add files in the current folder to the output sheet
    For Each FileItem In fso.GetFolder(FolderPath).Files ' fso 변수로 FileSystemObject 객체 사용
        Range("A" & i).Value = FolderPath
        Range("B" & i).Value = FileItem.Name
        i = i + 1
    Next FileItem
    
    ' Recursively loop through all subfolders in the current folder
    For Each SubFolder In fso.GetFolder(FolderPath).SubFolders ' fso 변수로 FileSystemObject 객체 사용
        SubFolderPath = SubFolder.Path & "\"
        ListFilesInFolderRecursive SubFolderPath, i
    Next SubFolder
    

 

End Sub

 

자 위 코드를 활용하면 다음과 같다

 

알트+f11로 모듈 삽입 후 코드 복사

 

도구-참조에 다음 사용가능한 참조 추가 마이크로 소프트 스크리핑 런타임

실행

폴더선택

 

모든 파일을 리스트업해주고, 파일경로도 적어주고, 마지막으로 동작한 시간까지 입력해준다.

 

이 함수는 엄청많은 파일들을 관리하는 사람이 사용하면 좋을것 같다.

 

사실 담당자 바뀌거나 하면 폴더가 뭐가있는지, 파일이 뭐가있는지 알기가 너무 어렵기 때문이다.

 

 

반응형