如何在一个目录中获取所有扩展名为ESY的文件列表?

16

在VBA中,我如何获取特定目录中特定扩展名的所有文件列表?

因为我使用的是Excel 2007,所以无法使用Application.FileSearch

4个回答

17

回应您的评论“那我需要运行多少次?”,此示例会一直运行,直到列出所有文件名与strPattern匹配的文件。请更改strFolder常量。

Public Sub ListESY()
Const strFolder As String = "C:\SomeFolder\"
Const strPattern As String = "*.ESY"
Dim strFile As String
strFile = Dir(strFolder & strPattern, vbNormal)
Do While Len(strFile) > 0
    Debug.Print strFile '<- view this in Immediate window; Ctrl+g will take you there
    strFile = Dir
Loop
End Sub

如果你想知道 Debug.Print 是做什么的,请查看这个链接:https://dev59.com/Q3E85IYBdhLWcg3wKwKD - ecoe

3

Dir("C:\yourPath\*.ESY", vbNormal) 返回第一个拓展名为esy的文件。 每次调用Dir()函数都会返回下一个。


1
测试WHILE或DO循环中结果的长度。 当长度为0时,表示完成。 - mohnston

2

另一种选择是使用“Microsoft Scripting Runtime”库(在工具...引用中检查),用于FileSystemObject对象系列。可能会像以下内容:

Public Function ESYFileCount(dir_path as String) as Long

Dim fil As File

    With New FileSystemObject
        With .GetFolder(dir_path)
            For Each fil In .Files
                If LCase(Right(fil.Name, 4)) = ".esy" Then
                    ESYFileCount = ESYFileCount + 1
                End If
            Next
        End With        
    End With

End Function

1
如果使用后期绑定而不是需要对FSO的引用,这段代码会更好(并且会让我点赞+1)。 - David-W-Fenton
@David-W-Fenton - 我不明白为什么晚期绑定会更好,能否解释一下? - Mike Woodhouse
3
由于域策略的阻止,Late binding更好。对于任何不属于默认访问引用集合的组件(有极少数例外),Late binding总是更好的选择。可以通过缓存对其的引用并在使用时使用缓存而避免性能损失,而无需每次都重新初始化它。 - David-W-Fenton
1
来自微软:尽可能使用早期绑定对象,因为它们允许编译器进行重要的优化。早期绑定对象比晚期绑定对象快得多,并且通过明确说明正在使用的对象类型,使代码更易于阅读和维护。早期绑定的另一个优点是它可以启用有用的功能,例如自动代码完成和动态帮助。早期绑定减少了运行时错误的数量和严重程度,因为它允许编译器在编译程序时报告错误。 - PBD10017
我对此有些晚了,但是在应用程序分布在具有不同标准和版本的系统上时,后期绑定也具有优势。 - Ryan B.
显示剩余2条评论

2
以下代码比使用FileSystemObject快约19倍。在我的电脑上,使用FileSystemObject查找三个不同目录中的4000个文件需要1.57秒,但是使用此代码仅需要0.08秒。
   Public Function CountFilesWithGivenExtension( _
          i_strFolderWithTerminalBackslant As String, _
          i_strExtensionIncludingPeriod As String _
          ) As Long

       If Len(Dir$(i_strFolderWithTerminalBackslant & "*" _
             & i_strExtensionIncludingPeriod)) > 0 Then

          CountFilesWithGivenExtension = 1

          While Len(Dir$) > 0

             CountFilesWithGivenExtension = _
                   CountFilesWithGivenExtension + 1

             DoEvents

          Wend
       Else
          CountFilesWithGivenExtension = 0
       End If

   End Function

示例用法:

   Debug.Print CountFilesWithGivenExtension("C:\", ".ex*")

(“DoEvents”不是必需的,但允许您在需要时使用暂停/中断。)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接