加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

vba 删除文件夹及其内容

(2014-03-15 10:35:23)
标签:

it

分类: excel_vba

VBA - Delete files and folders


Important
Read this page from Chip Pearson first
http://www.cpearson.com/excel/Recycle.htm
From Chip's site :
You need to remember, though, that Kill permanently deletes the file. 
There is no way to "undo" the delete. The file is not sent to the Windows Recycle Bin
( Same for the macro's that use the filesystemobject )

Sub DeleteExample1()
'You can use this to delete all the files in the folder Test
    On Error Resume Next
    Kill "C:\Test\*.*"
    On Error GoTo 0
End Sub
 
Sub DeleteExample2()
'You can use this to delete all xl? files in the folder Test
    On Error Resume Next
    Kill "C:\Users\Test\*.xl*"
    On Error GoTo 0
End Sub
 
Sub DeleteExample3()
'You can use this to delete one xls file in the folder Test
    On Error Resume Next
    Kill "C:\Users\Test\aa.xls"
    On Error GoTo 0
End Sub
 
Sub DeleteExample4()
'You can use this to delete the whole folder
'Note: RmDir delete only a empty folder
    On Error Resume Next
    Kill "C:\Users\a\Test\*.*"    ' delete all files in the folder
    RmDir "C:\Users\a\Test\"  ' delete folder
    On Error GoTo 0
End Sub
 
Sub Delete_Whole_Folder()
'Delete whole folder without removing the files first like in DeleteExample4
    Dim FSO As Object
    Dim MyPath As String
    Set FSO = CreateObject("scripting.filesystemobject")
    MyPath = "C:\Users\a\Test"  '<< Change
    If Right(MyPath, 1) = "\" Then
        MyPath = Left(MyPath, Len(MyPath) - 1)
    End If
    If FSO.FolderExists(MyPath) = False Then
        MsgBox MyPath & " doesn't exist"
        Exit Sub
    End If
    FSO.deletefolder MyPath
End Sub

Sub Clear_All_Files_And_SubFolders_In_Folder()
'Delete all files and subfolders
'Be sure that no file is open in the folder
    Dim FSO As Object
    Dim MyPath As String
    Set FSO = CreateObject("scripting.filesystemobject")
    MyPath = "C:\Users\a\Test"  '<< Change
    If Right(MyPath, 1) = "\" Then
        MyPath = Left(MyPath, Len(MyPath) - 1)
    End If
    If FSO.FolderExists(MyPath) = False Then
        MsgBox MyPath & " doesn't exist"
        Exit Sub
    End If
    On Error Resume Next
    'Delete files
    FSO.deletefile MyPath & "\*.*", True
    'Delete subfolders
    FSO.deletefolder MyPath & "\*.*", True
    On Error GoTo 0
End Sub
Comments
You do not have permission to add comments.

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有