How to get list of all files with ESY extension in a directory?

…衆ロ難τιáo~ 提交于 2019-11-28 10:57:41

In response to your comment "so how many times do i know to run it?", this example runs until it lists all the files whose names match strPattern. Change the strFolder constant.

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

Dir("C:\yourPath\*.ESY", vbNormal) Returns the first file with esy extension. Each subsequent call to Dir() returns the next.

Alternative option: use the "Microsoft Scripting Runtime" library (check it in Tools...References) for the FileSystemObject family of objects. Something like the following, perhaps:

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

The following code runs about 19 times faster than using FileSystemObject. On my machine, finding 4000 files in three different drectories took 1.57 seconds using FileSystemObject, but only 0.08 seconds using this code.

   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

Sample usage:

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

(The "DoEvents" is not necessary, but allows you to use Pause/Break if needed.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!