循环进入文件夹并删除.xlsm文件VBA

时间:2018-10-12 13:14:47

标签: vba excel-vba

亲爱的

我创建了一个代码来循环访问文件夹并删除10年之久的文件,但是由于FolderPath(变量)保持不变并且循环遵循无限循环,因此循环无法正常工作。有帮助吗?

Sub LoopThroughFolder()

Dim FolderPath As String

FolderPath = Dir("C:\Users\XXXX\XXXX\XXXX\XXXX\XXXX\*.xlsm")

 Do While FolderPath <> ""
    If DateValue( _
                    Mid(FolderPath, InStr(FolderPath, ".") + 1, 2) & "/" & _
                    Mid(FolderPath, InStr(FolderPath, ".") + 3, 2) & "/" & _
                    Mid(FolderPath, InStr(FolderPath, ".") + 5, 4)) _
        < DateValue(Date - 10) Then

        Application.DisplayAlerts = False
            SetAttr "C:\Users\XXXX\XXXX\XXXX\XXXX\XXXX\" & FolderPath, vbNormal
            Kill "C:\Users\XXXX\XXXX\XXXX\XXXX\XXXX\" & FolderPath
        Application.DisplayAlerts = True

        FolderPath = Dir

    End If
Loop

End Sub

1 个答案:

答案 0 :(得分:3)

您需要移动FolderPath = Dir, 当前它位于IF语句中,这意味着仅当当前文件的日期早于10天时,它才会查找下一个文件。

Sub LoopThroughFolder()

Dim FolderPath As String

FolderPath = Dir("C:\Users\XXXX\XXXX\XXXX\XXXX\XXXX\*.xlsm")

 Do While FolderPath <> ""
    If DateValue( _
                    Mid(FolderPath, InStr(FolderPath, ".") + 1, 2) & "/" & _
                    Mid(FolderPath, InStr(FolderPath, ".") + 3, 2) & "/" & _
                    Mid(FolderPath, InStr(FolderPath, ".") + 5, 4)) _
        < DateValue(Date - 10) Then

        Application.DisplayAlerts = False
            SetAttr "C:\Users\XXXX\XXXX\XXXX\XXXX\XXXX\" & FolderPath, vbNormal
            Kill "C:\Users\XXXX\XXXX\XXXX\XXXX\XXXX\" & FolderPath
        Application.DisplayAlerts = True
    End If
  FolderPath = Dir
Loop

End Sub