I want to move files to created folders. I got a mismatch error every time.
The aim is to create a folder named after the file prefix if it doesn't exist and copy the file to that folder.
I get
mismatch error
Sub loopf()
Dim AcceptedPrefixes As Object
Set AcceptedPrefixes = CreateObject("Scripting.Dictionary")
Dim PrefixRange As Range
Set PrefixRange = ThisWorkbook.Sheets(1).Range("B2:B368")
Dim Cell As Range
For Each Cell In PrefixRange.Cells
If Cell <> "" And Not AcceptedPrefixes.exists(Cell.Value) Then
AcceptedPrefixes.Add CStr(Cell.Value), 0
End If
Next
Dim Directory As String
Directory = "C:\TEST\"
Dim fsoFSO
Set fsoFSO = CreateObject("Scripting.FileSystemObject")
Dim filen As Variant
filen = Dir(Directory)
While filen <> ""
Dim FilePrefix As String
FilePrefix = "" & (Split(filen, "_")(0)) & ""
If Not AcceptedPrefixes.exists(FilePrefix) Then
Kill Directory & filen
Else
If fsoFSO.FolderExists("C:\TEST\" & FilePrefix) Then
'DO NOTHING
Else: fsoFSO.CreateFolder ("C:\TEST\" & FilePrefix) 'ELSE CREATE A FOLDER
' HERE i WANT TO MOVE THE FILES TO TRHE CREATED FOLDER OR EXISTING FOLDER
fso.MoveFile "C:\TEST\ & Filen", "C:\TEST\ & FilePrefix&" \ ""
End If
End If
filen = Dir
Wend
End Sub
Ok. I did solve it in the end—as in it does its job. Instead of to
fso.MoveFileI usedNameand it worked for my purpose. Still unclear whyfso.Movefiledidn't work.The whole code is below if anyone is interested.