我正在使用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
...
但是它的行为完全一样,在子中调用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\"
...
答案 0 :(得分:1)
您使用递归来走树。这是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