我想使用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
它给我一个错误,说找不到文件。但是我在文件夹中有一个需要删除的文件。
需要一些指导。
答案 0 :(得分:4)
使用以下内容应该按要求进行。请注意,最好使用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等。