1

I added a For loop (see k part) and it really slows down my entire program. Is it possible make this more efficient?

I am searching a specific folder and trying to match each file to a table in my spreadsheet. I am trying to make Quarters(1,j) in the For k loop same as Quarters(i,j) from the lower part of the code but not sure how to do that since I have already used integer 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
4

1 回答 1

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
于 2013-08-01T16:25:17.020 回答