如何获取目录中具有ESY扩展名的所有文件的列表?

时间:2010-06-10 18:28:46

标签: vba search filesystems excel-2007 file-extension

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

我无法Application.FileSearch,因为我正在使用excel 2007

4 个答案:

答案 0 :(得分:12)

为了回应您的评论“所以我知道运行它多少次?”,此示例将一直运行,直到列出名称与 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

答案 1 :(得分:3)

Dir(“C:\ yourPath \ * .ESY”,vbNormal) 返回带有esy扩展名的第一个文件。 每次后续调用Dir()都会返回下一个。

答案 2 :(得分:2)

备用选项:对FileSystemObject系列对象使用“Microsoft Scripting Runtime”库(在“工具...”参考中查看)。可能如下所示:

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

答案 3 :(得分:2)

以下代码的运行速度比使用FileSystemObject快19倍。在我的机器上,使用FileSystemObject在三个不同的drector中查找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”不是必需的,但允许您在需要时使用Pause / Break。)