Excel VBA – 使用Dir()的多个实例?

我正在使用excel将大型文件结构迁移到新文件夹,并重新sorting许多文件夹。 我正在使用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 

…并将其replace为原始代码

 ... AppsAwards newFolderDir, oldFolderPath, folder ... 

但是,它的行为完全一样,子内的Dir调用覆盖原始的Dir。

有没有办法有两个Dir()的实例? 如果没有,是否有解决方法呢?

编辑(解决scheme):

感谢面条一个很好的解决方法。 这是我在我的代码中实现它…

 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\" ... 

您使用recursion来走树。 这是VBScript如此可以进入VBA。 PS帮助说, Visual Basic允许您以两种不同的方式处理驱动器,文件夹和文件:通过传统方法(如Open语句,Write#等等),以及通过一组新工具,文件系统对象( FSO)对象模型。

 'On Error Resume Next Set fso = CreateObject("Scripting.FileSystemObject") Dirname = InputBox("Enter Dir name") 'Searchterm = Inputbox("Enter search term") ProcessFolder DirName Sub ProcessFolder(FolderPath) On Error Resume Next Set fldr = fso.GetFolder(FolderPath) Set Fls = fldr.files For Each thing in Fls msgbox Thing.Name & " " & Thing.path Next Set fldrs = fldr.subfolders For Each thing in fldrs ProcessFolder thing.path Next End Sub