使用前要引用Microsoft Scripting Runtime类型库。- Dim fso As Scripting.FileSystemObject
- '采用递归算法操作文件夹
- Sub DeleteSubFiles(ByVal PathName As String)
- Dim f As Folder
- Dim ff As File
- Dim sf As Folder
-
- '返回文件夹
- Set f = fso.GetFolder(PathName)
- '遍历文件
- For Each ff In f.Files
- If Len(ff.Name) > 3 Then
- If StrComp(Right(ff.Name, 3), "BAK", vbTextCompare) = 0 Then
- '强制删除文件
- ff.Delete True
- End If
- End If
- Next
- '遍历子文件夹
- For Each sf In f.SubFolders
- DeleteSubFiles sf.Path
- Next
- Set sf = Nothing
- Set ff = Nothing
- Set f = Nothing
- End Sub
- Sub DeleteBakFiles(ByVal PathName As String)
- Set fso = New Scripting.FileSystemObject
- '判断文件夹是否存在
- If Not fso.FolderExists(PathName) Then Exit Sub
- DeleteSubFiles PathName
- Set fso = Nothing
- End Sub
- Sub Test()
- DeleteBakFiles "c:"
- End Sub
|