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

莱克什

我想使用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

这给我一个错误,提示找不到文件。但是我的文件夹中有一个文件需要删除。

需要一些指导。

西蒙1979

根据需要使用以下内容。请注意,最好使用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等。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章