How to get list of all files with ESY extension in

2019-01-18 22:45发布

问题:

In VBA, how do I get a list of all the files with a specific extension in a specific directory?

i am unable to do Application.FileSearch, because i am using excel 2007

回答1:

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


回答2:

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



回答3:

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


回答4:

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.)