【问题标题】:Searching a folder to match each file to a table搜索文件夹以将每个文件与表匹配
【发布时间】:2013-08-01 15:36:14
【问题描述】:

我添加了一个 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) Set objFSO = CreateObject("Scripting.FileSystemObject") 应该在所有循环之外。 (2)SourceFolderName = FolderPath &amp; "\" &amp; Quarters(1, j) Set objFolder = objFSO.GetFolder(SourceFolderName) 应该在k 循环之外,因为它只使用i 变量。 (3) 我认为您可以将DIR 与通配符一起使用,而不是测试每个文件。见stackoverflow.com/questions/10380312/…
  • 您好,我不确定如何使用 DIR 进行转换。原因是我有太多的循环和条件。你能帮我解决这个问题吗?谢谢。
  • 谢谢@brettdj。在你提到之前,我永远不会想到 DIR。现在我的运行时间从 40 分钟减少到 2 秒。谢谢!!!对于那些感兴趣的人,我将我的解决方案发布在顶部。

标签: vba excel for-loop excel-2010


【解决方案1】:

我设法将整个代码更改为使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 2019-09-14
    • 2010-09-23
    • 2013-01-08
    • 1970-01-01
    相关资源
    最近更新 更多