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

vb

by 팁텍북 2024. 7. 5.

Sub DeleteFiles()
    Dim folderPath As String
    Dim FSO As Object
    Dim folder As Object
    Dim file As Object
    Dim aFiles As Collection
    Dim bFiles As Collection
    Dim latestAFile As Object
    Dim latestBFile As Object
    Dim latestADate As Date
    Dim latestBDate As Date
    
    ' 폴더 경로 설정
    folderPath = "C:\abc\"
    
    ' FileSystemObject 생성
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Set folder = FSO.GetFolder(folderPath)
    
    ' Collection 초기화
    Set aFiles = New Collection
    Set bFiles = New Collection
    
    ' 폴더 내 파일 탐색
    For Each file In folder.Files
        If InStr(file.Name, "a") > 0 Then
            aFiles.Add file
        ElseIf InStr(file.Name, "b") > 0 Then
            bFiles.Add file
        End If
    Next file
    
    ' a가 포함된 파일 중 가장 최근 수정된 파일 찾기
    If aFiles.Count > 0 Then
        latestADate = #1/1/1900#
        For Each file In aFiles
            If file.DateLastModified > latestADate Then
                Set latestAFile = file
                latestADate = file.DateLastModified
            End If
        Next file
    End If
    
    ' b가 포함된 파일 중 가장 최근 수정된 파일 찾기
    If bFiles.Count > 0 Then
        latestBDate = #1/1/1900#
        For Each file In bFiles
            If file.DateLastModified > latestBDate Then
                Set latestBFile = file
                latestBDate = file.DateLastModified
            End If
        Next file
    End If
    
    ' a가 포함된 파일 삭제 (가장 최근 수정된 파일 제외)
    For Each file In aFiles
        If Not file Is latestAFile Then
            file.Delete
        End If
    Next file
    
    ' b가 포함된 파일 삭제 (가장 최근 수정된 파일 제외)
    For Each file In bFiles
        If Not file Is latestBFile Then
            file.Delete
        End If
    Next file
    
    ' 정리
    Set FSO = Nothing
    Set folder = Nothing
    Set aFiles = Nothing
    Set bFiles = Nothing
    Set latestAFile = Nothing
    Set latestBFile = Nothing

    MsgBox "파일 정리가 완료되었습니다."
End Sub

댓글