我想使用Excel2010中的vba遍历目录中的文件。
在循环中,我需要:
我已经编写了以下代码,如果文件夹有不超过50个文件的工作很好,否则它是荒谬的慢(我需要它与>10000个文件的文件夹工作)。这段代码的唯一问题是查找file.name的操作花费了非常多的时间。
运行正常但速度太慢的代码(每100个文件15秒):
Sub LoopThroughFiles()
   Dim MyObj As Object, MySource As Object, file As Variant
   Set MySource = MyObj.GetFolder("c:\testfolder\")
   For Each file In MySource.Files
      If InStr(file.name, "test") > 0 Then
         MsgBox "found"
         Exit Sub
      End If
   Next file
End Sub解决了问题:
Dir ( 15000个文件使用20秒),并使用FileDateTime命令检查时间戳。发布于 2017-08-18 14:09:42
下面是我对函数的解释:
'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String
    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile
    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir
    Loop
End Function发布于 2012-04-30 19:23:18
Dir采用通配符,因此您可以在前面为test添加过滤器,从而避免测试每个文件
Sub LoopThroughFiles()
    Dim StrFile As String
    StrFile = Dir("c:\testfolder\*test*")
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir
    Loop
End Sub发布于 2012-04-30 16:08:02
Dir似乎非常快。
Sub LoopThroughFiles()
    Dim MyObj As Object, MySource As Object, file As Variant
   file = Dir("c:\testfolder\")
   While (file <> "")
      If InStr(file, "test") > 0 Then
         MsgBox "found " & file
         Exit Sub
      End If
     file = Dir
  Wend
End Subhttps://stackoverflow.com/questions/10380312
复制相似问题