2010-06-10 120 views

回答

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 
+0

看到这个:http://stackoverflow.com/questions/2916287/where-does-vba-debug-print-log-to – ecoe 2014-04-04 18:22:21

3

迪尔( “C:\ yourPath \ * ESY”,vbNormal) 返回与ESY扩展的第一个文件。 每个后续调用Dir()都会返回下一个。

+0

很大,所以多少次,我知道运行它? – 2010-06-10 18:59:40

+1

在WHILE或DO循环中测试结果的长度。 当长度为0时,你就完成了。对于那些好奇的“Debug.Print”, – mohnston 2010-06-10 19:02:12

2

替代选项:使用FileSystemObject对象系列对象的“Microsoft Scripting Runtime”库(在Tools ... References中检查它)。或许如下:

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。 – 2010-06-12 00:37:14

+0

@ David-W-Fenton - 我不明白为什么晚结合会更好,谨慎解释? – 2010-06-12 13:57:34

+2

由于域策略可以阻止FSO的自动化,所以后期绑定更好。对于任何不属于默认访问集合引用的组件,极少的绑定总是*更好(极少数例外)。通过缓存对它的引用可以轻松避免性能下降,并且可以避免每次使用时重新初始化它。 – 2010-06-12 20:15:47

1

以下代码运行速度比使用FileSystemObject快大约19倍。在我的机器上,使用FileSystemObject在三个不同的drectories中查找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” 是没有必要的,但是允许你使用暂停/如果必要的休息。)

相关问题