【发布时间】: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 & "\" & 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