1
我添加了一個For循環(見k部分),它確實減慢了我的整個程序。有沒有可能讓這個更有效率?搜索文件夾以匹配每個文件到表
我正在搜索特定文件夾,並嘗試將每個文件與電子表格中的表格進行匹配。我試圖讓Quartus(1,j)在For循環中與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,而不是測試每個文件。請參閱http://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba/10382861#10382861 – brettdj
嗨,我不知道如何使用DIR進行轉換。原因是我有太多的循環和條件正在進行。你能幫助我嗎?謝謝。 – Futochan
謝謝@brettdj。直到你提到之前,我都不會想到DIR。現在我的運行時間從40分鐘減少到2秒。謝謝!!!對於那些有興趣的人,我把我的解決方案放在最前面。 – Futochan