vba 删除文件夹中的所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44162807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:50:43  来源:igfitidea点击:

Delete all files in a folder

vbafilekill

提问by Brentford123

I have the below code to try search for all files in my downloads folder and then delete them all however it's returning an error message based on the kill function not having enough arguments, any ideas?

我有下面的代码来尝试搜索我的下载文件夹中的所有文件,然后将它们全部删除,但是它返回一条基于 kill 函数没有足够参数的错误消息,有什么想法吗?

Sub Kill ()

Dim aFile As String
aFile = "C:\Test\Test\Downloads\*.*"
If Len(Dir$(aFile)) > 0 Then
    Kill aFile
End If

End Sub

Thanks,

谢谢,

回答by Delmar Silva

A more simple way:

更简单的方法:

Sub Del()
  Kill "C:\FolderName\*.*"
End Sub

回答by ja72

Add a reference to Microsoft Scripting Runtimein the VBA environment

Microsoft Scripting Runtime在VBA环境中添加对的引用

ref

参考

scr

可控硅

The declare in a Modulethe following line

Module在以下行中声明

Global fso As New FileSystemObject

Now you can use all the nice and modern I/O functions. For example:

现在您可以使用所有漂亮且现代的 I/O 功能。例如:

Public Sub TDELFOL()    
    Dim path As String, f As File
    path = fso.GetSpecialFolder(TemporaryFolder)
    path = fso.BuildPath(path, "MyTempFolder")
    If fso.FolderExists(path) Then
        For Each f In fso.GetFolder(path).Files
            f.Delete Force = True
        Next
        fso.DeleteFolder path, Force = True
    End If
End Sub

回答by Ramesh Bhoopathy Raju

You should notname macros as the in built functions. Just changing the macros with the same coding resolves the issues...

您不应宏命名为内置函数。只需更改具有相同编码的宏即可解决问题...

Sub Kill1 ()

Dim aFile As String
aFile = "C:\Test\Test\Downloads\*.*"
If Len(Dir$(aFile)) > 0 Then
    Kill aFile
End If

End Sub