【发布时间】:2017-04-25 09:33:34
【问题描述】:
我正在使用 excel 将一个大文件结构迁移到一个新文件夹并重新排序许多文件夹。我正在使用 Dir() 函数循环浏览每个文件夹,还循环浏览文件......但我遇到了第二个 Dir() 函数覆盖第一个的问题。有没有办法设置两个 Dir() 实例?
Sub GetFolders()
Dim oldFolderPath As String
Dim folder As String
Dim copyFolderDir As String
Dim newFolderDir As String
Dim strFile As String
oldFolderPath = "C:\Users\jordanharris\Desktop\PATIENT FILES\A\"
newFolderDir = "C:\Users\jordanharris\Desktop\PATIENT FILES\A v2\"
'The goal here is to loop through every file in a folder (without knowing how many or their names)
folder = Dir(oldFolderPath, vbDirectory) 'First Dir()
Do While folder <> ""
If (GetAttr(oldFolderPath & folder) And vbDirectory) = vbDirectory Then
MkDir newFolderDir & folder & "\APPS-AWARDS\"
copyFolderDir = oldFolderPath & folder & "\DWSS-EA\"
'The goal here is to copy every file in the folder 'DWSS-EA' to the new folder 'APPS-AWARDS'
strFile = Dir(copyFolderDir & "*.*") ' This Dir is overwriting the Dir above
Do While Len(strFile) > 0
Name copyFolderDir & strFile As newFolderDir & folder & "\APPS-AWARDS\" & strFile
'Get next file using Dir
strFile = Dir()
Loop
End If
'Get Next Folder using Dir
folder = Dir() 'Error on this line because Dir is being overwritten
Loop
End Sub
如您所见,我使用了两个 Dir 实例,这导致了我无法转到下一个文件夹的错误。我原本以为我只是将 Dir 的第二个实例放在它自己的 Sub 中,就像这样......
Sub AppsAwards (newFolderDir As String, oldFolderPath As String, folder As String)
MkDir newFolderDir & folder & "\BENEFITS\APPS-AWARDS\"
copyFolderDir = oldFolderPath & folder & "\DWSS-EA\"
strFile = Dir(copyFolderDir & "*.*")
Do While Len(strFile) > 0
Name copyFolderDir & strFile As newFolderDir & folder & "\BENEFITS\APPS-AWARDS\" & strFile
strFile = Dir()
Loop
End Sub
... 并调用它来代替原始代码...
...
AppsAwards newFolderDir, oldFolderPath, folder
...
但它的作用完全相同,在 sub 中调用 Dir 会覆盖原始 Dir。
有没有办法拥有两个 Dir() 实例?如果没有,是否有解决方法?
编辑(解决方案):
感谢 Noodles 提供了一个很好的解决方法。这就是我在代码中实现它的方式...
Sub ProcessFolder(FolderPath As String, newFolderPath As String)
On Error Resume Next
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder(FolderPath)
Set fls = fldr.Files
For Each Thing In fls
Name FolderPath & Thing.Name As newFolderPath & Thing.Name
Next
End Sub
然后我将这一行放在我的原始代码中......
...
ProcessFolder oldFolderPath & folder & "\DWSS-EA\", newFolderDir & folder & "\BENEFITS\APPS-AWARDS\"
...
【问题讨论】:
-
简而言之,没有。请改用
Scripting.FileSystemObject。 -
我遇到了类似的需求,发现我可以构建数组。我循环浏览一个查看文件夹的 Dir() 集,并将这些目录位置分配给一个变量。然后我可以在每个文件夹路径中使用另一个 Dir() 集并收集另一个文件名数组。不过,我的案例的文件和文件夹结构非常结构化,因此它可能不适用于所有情况。