有3個方法:
1. 單純使用kill 指令,
缺點,只能砍層目錄,而且必須要有檔案,否則會Error (直接刪除)
Sub DeleteExample1()
'You can use this to delete all the files in the folder Test
On Error Resume Next
Kill "C:\Users\Ron\Test\*.*"
End Sub
2. 使用FSO去砍檔, 本範例是砍 "c:\新資料夾" 內所有資料 (直接刪除)
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:\新資料夾" '<< 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
3. 呼叫API去砍檔 ,可選擇是否進資源回收桶
在主程式利用 delDoc "c:\temp\output.txt" 砍c:\temp\output.txt檔案
利用 delDoc "c:\temp" '砍整個temp資料夾
=====程式碼===========
Option Explicit
Private Const FO_DELETE = &H3
Private Const FOF_NOCONFIRMATION = &H10
Private Const FOF_ALLOWUNDO = &H40
Private Type SHFILEOPSTRUCT
hWnd As Long
wFunc As Long
pFrom As String
pTo As String
fFlags As Integer
fAborted As Boolean
hNameMaps As Long
sProgress As String
End Type
Private Declare Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
Public Sub delDoc(thePath)
Dim S As SHFILEOPSTRUCT
With S
.wFunc = FO_DELETE
.pFrom = thePath '→欲刪除之資料夾
'丟到資源回收桶
.fFlags = FOF_ALLOWUNDO + FOF_NOCONFIRMATION
'直接刪除
'.fFlags = FOF_NOCONFIRMATION
End With
SHFileOperation S
End Sub
========================
留言列表