【发布时间】:2015-02-04 04:02:57
【问题描述】:
我想使用 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
它给了我一个错误,说找不到文件。但是我的文件夹中有一个文件需要删除。
需要一些指导。
【问题讨论】:
-
检查文件是否存在于给定位置。
-
它就在那里。我确保了这一点。
-
我意识到这有点编辑性,但我建议不要使用不能准确表示其中存储的数据的变量名称:具体而言,可能不应该使用名为
folderPath的变量存储文件名。 -
使用 FSO 对象来识别文件并将其排除在删除操作之外。
-
@PareshJ 可以给我看一个例子。