You have to change the following line:
If Dir(ToPath & fileName) = "" Then
To
If Dir(ToPath & fileName, 7) = "" Then
The check for read-only, system, or hidden files is not being done by that line. Hence, your code tries to rename a hidden file that already exists.
You might want to try this version of your code, which, because it doesn't traverse through the entire directory each time, should perform better in large directories.
Function OldestFile(strFold As String) As Variant
Dim FSO As Object, Folder As Object, File As Object, oldF As String
Dim lastFile As Date: lastFile = Now
Set FSO = CreateObject("Scripting.FileSystemObject")
Set Folder = FSO.GetFolder(strFold)
Dim myarray As Variant
If Folder.Files.Count > 0 Then
ReDim myarray(Folder.Files.Count - 1)
ix = 0
For Each File In Folder.Files
myarray(ix) = Format(File.DateCreated, "YYYYMMDDHHmmSS") & File.Name
ix = ix + 1
Next
For i = LBound(myarray) To UBound(myarray) 'Sort according to date
For j = i + 1 To UBound(myarray)
If UCase(myarray(i)) > UCase(myarray(j)) Then
Temp = myarray(j)
myarray(j) = myarray(i)
myarray(i) = Temp
End If
Next j
Next i
End If
OldestFile = myarray
End Function
Sub MoveOldestFile()
Dim FromPath As String, ToPath As String, fileName As String, limit As Long
Dim fileArray As Variant
FromPath = "C:\Users\user\Desktop\Source\"
ToPath = "C:\Users\user\Desktop\Destination\"
limit = 20
filesmoved = 0
fileArray = OldestFile(FromPath)
If Not IsEmpty(fileArray) Then
ix = 0
Do Until ix > UBound(fileArray) Or filesmoved = limit
fileName = Mid(fileArray(ix), 15)
If Dir(ToPath & fileName, 7) = "" Then
Name FromPath & fileName As ToPath & fileName
filesmoved = filesmoved + 1
End If
ix = ix + 1
Loop
End If
End Sub