搜索文件夹以将每个文件与表匹配

时间:2013-07-31 22:03:14

标签: excel vba excel-vba for-loop excel-2010

我添加了For循环(参见k部分),它确实减慢了我的整个程序。是否有可能提高效率?

我正在搜索特定文件夹,并尝试将每个文件与电子表格中的表格相匹配。我试图在For k循环中使Quarters(1,j)与Quarters(i,j)相同,但是由于我已经使用了整数i,所以不知道该怎么做。

For j = 1 To 2
    For k = 1 To 39
        If k <= 29 Then
            'Looks at all the files in the folder for the given Quarter
            SourceFolderName = FolderPath & "\" & Quarters(1, j)
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objFSO.GetFolder(SourceFolderName)
        End If

        If k > 29 Then
            SourceFolderName = FolderPath & "\" & Quarters(k, j)
            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objFSO.GetFolder(SourceFolderName)
        End If

        For Each objFile In objFolder.Files
            i = 1
            NotAssigned = True
            'Keep going until we match the file
            While NotAssigned = True
                'If the beginning of the file name matches for a given state,
                'assign the file name to that state for this quarter
                If Left(objFile.Name, 9) = StateAbbr(i, 1) & Quarters(i, j) & "FA" Then
                    WBName(i, j) = objFile.Name
                    'Stop trying to match the file 
                    NotAssigned = False
                End If
                If i = 39 Then NotAssigned = False
                i = i + 1
            Wend
        Next objFile
        Set objFile = Nothing
        Set objFolder = Nothing
        Set objFSO = Nothing
    Next k
Next j

1 个答案:

答案 0 :(得分:2)

我设法将整个代码更改为使用DIR而不是在电子表格中循环每个单元格并循环我的文件夹中的每个文件。我的运行时间从40分钟减少到2秒!!!!!!!我现在对此感到非常惊讶。如果您有兴趣,可以使用以下解决方案。

Dim StrFile As String
For j = 1 To 2
    For i = 1 To 39
        StrFile = Dir(FolderPath & "\" & Quarters(i, j) & "\*FA*")
    Do While Len(StrFile) > 0
        If Left(StrFile, 9) = StateAbbr(i, 1) & Quarters(i, j) & "FA" Then
            WBName(i, j) = StrFile
        End If
        StrFile = Dir
    Loop
    Next i  
Next j