Kill是直接删除,回收站找不到文件。
因为 VBA 本身没有直接操作回收站的内置方法。
方法一(Shell.Application)通过创建Shell.Application对象,调用其Namespace(10).MoveHere方法(Namespace(10)对应系统回收站),本质是模拟 Windows 资源管理器的操作,属于COM 组件调用。
Sub 移动文件到回收站()
Set xShell = CreateObject("Shell.Application")
fpath = "C:\Users\Administrator\Desktop\客户收款.zip" '指定文件<包括路径>
Call xShell.Namespace(10).MoveHere(fpath)
End Sub
方法二(SHFileOperation API)直接调用 Windows 系统 API 函数SHFileOperation(shell32.dll),通过配置结构体参数指定删除操作并允许撤销(FOF_ALLOWUNDO),属于底层系统接口调用。
Option Explicit
' 声明Windows API函数(用于将文件移至回收站)
Private Declare PtrSafe Function SHFileOperation Lib "shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
' 定义API所需的结构体
Private Type SHFILEOPSTRUCT
hwnd As LongPtr ' 窗口句柄(可设为0)
wFunc As Long ' 操作类型(FO_DELETE=3表示删除)
pFrom As String ' 源文件路径(必须以双null结尾)
pTo As String ' 目标路径(删除操作时可为空)
fFlags As Integer ' 操作标志(FOF_ALLOWUNDO=&H40表示允许撤销,即移至回收站)
fAnyOperationsAborted As Long
hNameMappings As LongPtr
lpszProgressTitle As String
End Type
' 移动文件到回收站的函数
Public Function MoveFileToRecycleBin(filePath As String) As Boolean
Dim fileOp As SHFILEOPSTRUCT
Dim result As Long
' 检查文件是否存在
If Dir(filePath) = "" Then
MoveFileToRecycleBin = False
Exit Function
End If
' 配置结构体参数
With fileOp
.wFunc = 3 ' FO_DELETE:删除操作
.pFrom = filePath & vbNullChar & vbNullChar ' 路径需以两个空字符结尾
.fFlags = &H40 ' FOF_ALLOWUNDO:允许撤销(移至回收站)
End With
' 调用API执行操作
result = SHFileOperation(fileOp)
' 返回操作结果(0表示成功)
MoveFileToRecycleBin = (result = 0)
End Function
' 使用示例(测试用)
Sub TestMoveToRecycleBin()
Dim testFile As String
testFile = "C:\Test\example.txt" ' 替换为实际文件路径
If MoveFileToRecycleBin(testFile) Then
MsgBox "文件已成功移至回收站!", vbInformation
Else
MsgBox "操作失败(文件不存在或路径错误)", vbExclamation
End If
End Sub

885

被折叠的 条评论
为什么被折叠?



