gpt4 book ai didi

vba - 删除文件夹 VBA 中的非 Excel 文件

转载 作者:行者123 更新时间:2023-12-04 21:38:11 25 4
gpt4 key购买 nike

我想使用 VBA 删除文件夹中的非 Excel 文件。

这是我从这里找到的代码:Excel Delete Files .

Dim fName As String
fName = Dir("C:\test\*.*")
Do While fName <> ""
If fName <> "fileA.xls" Then'or .txt or .csv or whatever
Kill "C:\test\" & fName
End If
fName = Dir
Loop

我以这种方式更改了代码:
folderPath = Dir("C:\test\")
Do While folderPath <> ""
If folderPath <> "*.xls" Then'or .txt or .csv or whatever
Kill "C:\test\" & folderPath
End If
folderPath = Dir
Loop

它给我一个错误,说找不到文件。但是我在文件夹中有一个文件需要删除。

在这方面需要一些指导。

最佳答案

使用以下内容应按要求进行。请注意,最好使用 Like比较部分字符串的运算符,在本例中为 Not运算符只寻找那些不匹配的。

strFileName = Dir("C:\test\*")
Do While strFileName <> ""
If Not lcase$(strFileName) Like "*.xls" Then 'or .txt or .csv or whatever
Kill "C:\test\" & strFileName
End If
strFileName = Dir
Loop

请注意,如果您希望它忽略所有 Excel 文件,请考虑使用备用扩展名并使用 And 明确说明它们。如下:
If Not lcase$(strFileName) Like "*.xls" And Not lcase$(strFileName) Like "*.xlsx" Then
记住 .txt、.csv、.xlsm 等。

关于vba - 删除文件夹 VBA 中的非 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28313291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com