我创建了一个宏,将一组文件分发到各个子文件夹中。但是,我已经存在"文件已经存在"尝试移动文件时出错。它发生在第2和第3个oFSO.movefile语句中。有任何想法吗?我尝试添加" \"到文件名的末尾,但它给我一个类型不匹配错误?
PS。请耐心等待,我没有接受过VBA的正式培训。
谢谢!
Sub DistributeDD()
MsgBox ("To use this Macro, Place all loan numbers you want to create folders for in column A starting at A1 and the sponsor in column B or C")
SourceFolder = InputBox("Paste the Path where the files are located")
Dim oFSO
Dim oFolder As Object
Dim oFile As Object
Dim NewFolder As String
Dim myRange As Range
Dim i As Long
Dim TestString As String
LastRow = Range("A" & Rows.Count).End(xlUp).Row
Dim subfolder As String
Dim Sponsor As String
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(SourceFolder)
For i = 1 To LastRow
LoanID = Cells(i, 1).Value
Sponsor = Cells(i, 2).Value
Sponsor2 = Cells(i, 3).Value
For Each oFile In oFolder.Files
TestString = oFile.Name
'Populate Collateral File
If InStr(UCase(TestString), UCase(LoanID)) > 0 Then
NewFolder = LoanID
subfolder = IdentifySubfolder(TestString)
createNewDirectory (SourceFolder & "\" & NewFolder)
createNewDirectory (SourceFolder & "\" & NewFolder & "\" & subfolder)
oFSO.movefile Source:=oFile, Destination:=SourceFolder & "\" & NewFolder & "\" & subfolder & "\"
End If
'Populate Sponsor
If InStr(UCase(TestString), UCase(Sponsor)) > 0 Then
NewFolder = LoanID
subfolder = IdentifySubfolder(TestString)
createNewDirectory (SourceFolder & "\" & NewFolder)
createNewDirectory (SourceFolder & "\" & NewFolder & "\" & Sponsor)
oFSO.movefile Source:=oFile, Destination:=SourceFolder & "\" & NewFolder & "\" & Sponsor
MsgBox (TestString)
End If
'Populate Sponsor2
If InStr(UCase(TestString), UCase(Sponsor)) > 0 Then
NewFolder = LoanID
subfolder = IdentifySubfolder(TestString)
createNewDirectory (SourceFolder & "\" & NewFolder)
createNewDirectory (SourceFolder & "\" & NewFolder & "\" & Sponsor2)
createNewDirectory (SourceFolder & "\" & NewFolder & "\" & Sponsor2 & "\" & subfolder)
oFSO.movefile Source:=oFile, Destination:=SourceFolder & "\" & NewFolder & "\" & Sponsor2
End If
Next oFile
Next i
Set oFolder = Nothing
Set oFSO = Nothing
End Sub
答案 0 :(得分:-1)
列赞助商(2)和赞助商2(3)是否可能拥有相同的信息?如果是这样,在SourceFolder \ NewFolder下创建的文件夹将具有相同的名称。
此外,我不知道您为什么要使用文件名测试这些列,但是在第42行,您再次使用“赞助商”进行测试。
If InStr(UCase(TestString), UCase(Sponsor)) > 0 Then
根据您的数据,可能是问题的根源。