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

前端 未结 4 2013
野的像风
野的像风 2020-12-10 12:41

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 u

相关标签:
4条回答
  • 2020-12-10 12:57

    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
    
    0 讨论(0)
  • 2020-12-10 13:12

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

    0 讨论(0)
  • 2020-12-10 13:14

    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
    
    0 讨论(0)
  • 2020-12-10 13:22

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

    0 讨论(0)
提交回复
热议问题