본문 바로가기
카테고리 없음

참조사용하지 않는 코드. 폴더 탐색해서 시트정리

by 팁텍북 2024. 7. 23.

Sub ListExcelFiles()
    Dim folderPath As String
    folderPath = "C:\Your\Folder\Path"  ' 탐색할 폴더 경로를 여기에 입력하세요.

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")
    ws.Cells.Clear

    ListFilesInFolder folderPath, ws, 1
End Sub

Sub ListFilesInFolder(folderPath As String, ws As Worksheet, ByRef row As Long)
    Dim fileName As String
    Dim subFolder As String
    Dim currentPath As String
    
    ' 폴더 경로에 백슬래시 추가
    If Right(folderPath, 1) <> "\" Then folderPath = folderPath & "\"
    
    ' .xlsx 파일 검색
    fileName = Dir(folderPath & "*.xlsx")
    Do While fileName <> ""
        ws.Cells(row, 1).Value = folderPath & fileName
        row = row + 1
        fileName = Dir
    Loop
    
    ' 하위 폴더 검색
    subFolder = Dir(folderPath & "*", vbDirectory)
    Do While subFolder <> ""
        If subFolder <> "." And subFolder <> ".." Then
            currentPath = folderPath & subFolder & "\"
            If (GetAttr(currentPath) And vbDirectory) = vbDirectory Then
                ListFilesInFolder currentPath, ws, row
            End If
        End If
        subFolder = Dir
    Loop
End Sub

댓글