计数文件夹中的文件- Dir的奇怪行为

  • 本文关键字:Dir 文件 文件夹 excel vba
  • 更新时间 :
  • 英文 :


我正在使用下面的函数来计数文件夹sPath中某个文件类型sFileType的文件。

Function CountFilesInFolder(sPath As String, Optional sFileType As String) As Long
Dim vFile As Variant
Dim lFileCount As Long

If Right(sPath, 1) <> "" Then sPath = sPath & ""
vFile = Dir(sPath & sFileType)
While (vFile <> "")
lFileCount = lFileCount + 1
vFile = Dir
Wend

CountFilesInFolder = lFileCount
End Function

在包含:

的文件夹上测试函数时:
  • 2xls文件和
  • 3xlsx文件

Debug.Print CountFilesInFolder(“C:test”, “*.xls”)

我希望它返回2,然而,该函数也计数xlsx文件,它返回5

如果我测试函数

Debug.Print CountFilesInFolder(“C:test”, “*.xlsx”)

返回3,和预期的一样。为什么第一个示例中的函数也对xlsx文件进行计数?我没有指定任何通配符,但仍然Dir的行为类似于它。我做错什么了吗?我可能会在While/Wend中添加If语句,但我假设我在Dir函数中做错了什么。

From: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/dir#:~:text=The%20asterisk%20wildcard%20always%20uses%20short%20file%20name%20mapping%2C%20so%20you%20might%20get%20unexpected%20results.%20For%20example%2C%20the%20following%20directory%20contains%20two%20files%20(t.txt2%20and%20t97.txt)%3A

星号通配符总是使用短文件名映射,所以您可能会得到意想不到的结果。

带有(例如)"xlsx"/"xlsm"/etc扩展名all的Windows短名称以".XLS"结尾

更详细的概述在上面评论的GSerg的链接。

相关内容

最新更新