【问题标题】:Delete non-Excel Files in a folder VBA删除文件夹 VBA 中的非 Excel 文件
【发布时间】: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 可以给我看一个例子。

标签: vba excel


【解决方案1】:

使用下面的应该按要求做。请注意,最好使用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 等

【讨论】:

  • 应该也应该lcase$(strFileName) like ...
猜你喜欢
  • 2021-01-17
  • 2016-05-28
  • 2012-06-18
  • 1970-01-01
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
  • 2017-02-11
  • 2012-06-03
相关资源
最近更新 更多