Dim FSO, agoDays, CreatedDate, delFolder ' 宣告變數
'要刪除目錄層級
Const KillPathCount = 2
Private Sub Command1_Click()
'要刪除的主目錄
delFolder = "F:\SCRIPT"
' 建立檔案系統物件(File System Object)
Set FSO = CreateObject("Scripting.FileSystemObject")
' 呼叫刪除資料夾的副程式
DelFilesInFolder FSO.GetFolder(delFolder)
MsgBox "OK"
End Sub

 

'取得Path的層級
Function GetPathLevel(path)
Dim result
result = 0
Dim pos
pos = 0
Do
pos = InStr(pos + 1, path, "\")
If pos > 0 Then
result = result + 1
End If
Loop Until pos = 0
GetPathLevel = result
End Function

 

'要刪除某個目錄下某一層的檔及目錄
Sub DelFilesInFolder(folder)
Dim subFolder ' 宣告變數
' 找出目前所在目錄內所有的目錄
For Each subFolder In folder.SubFolders
Dim folderPath
folderPath = subFolder.path
'如果目錄大於KillPathCount層就刪掉
Dim pathLevel
pathLevel = GetPathLevel(folderPath)
If pathLevel > KillPathCount Then
'先把目錄的檔刪除
'如果下面還有subFolder要先刪掉
If subFolder.SubFolders.Count > 0 Then
Call DelFilesInFolder(subFolder)
End If
If FSO.FolderExists(folderPath) Then
Call FSO.DeleteFolder(folderPath)
End If

 

ElseIf pathLevel = KillPathCount Then
'要刪除檔
FSO.DeleteFile subFolder & "\*.*"
Call DelFilesInFolder(subFolder)
Else
Call DelFilesInFolder(subFolder)
End If
Next
End Sub
創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()