Hi I am seeking help to fix the below VBA. This should move the listed files in column M to Archive folder, and rename by adding version number for the files that exist in Archive folder. The Archive folder is located in the same folder where the macro-enabled excel file and the listed files are located. The list of filenames are in M5:M(last non blank row) and the names include file extensions (i.e PETROVIE 01012021.pdf).
The below code only moves the files that do not exist in Archive folder, but cannot rename the file in current folder and then move to Archive folder.
Can somebody please help me fix this code?
==VBA Code==
Sub MoveFiles()
On Error GoTo Errproc
Dim sFromPath As String
Dim sDestPath As String
Dim k As Integer
'Const sFileType As String = ".pdf"
sFromPath = ActiveWorkbook.Path & "\"
sDestPath = sFromPath & "Archive\"
'validate destination folder
If Len(Dir(sDestPath)) = 0 Then
MsgBox "Destination path does not exist..."
Exit Sub
End If
Dim iRow As Integer
iRow = Range("M" & Rows.Count).End(xlUp).Row
Dim rr As Range, r As Range
Dim FileName As String
Set rr = Range("M5:M" & iRow)
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each r In rr
With objFSO
If Not .FileExists(sDestPath & r.Value) Then
objFSO.MoveFile Source:=sFromPath & r.Value, Destination:=sDestPath
Else
FileName = r.Value
Do Until .FileExists(sDestPath & FileName) = 0
k = k + 1
FileName = Replace(FileName, ".pdf", "-" & k & ".pdf")
Loop
objFSO.MoveFile Source:=sFromPath & FileName, Destination:=sDestPath
End If
End With
Next r
Leave:
Set objFSO = Nothing
On Error GoTo 0
Exit Sub
Errproc:
MsgBox Err.Description, vbCritical
Resume Leave
End Sub
The below code only moves the files that do not exist in Archive folder, but cannot rename the file in current folder and then move to Archive folder.
Can somebody please help me fix this code?
==VBA Code==
Sub MoveFiles()
On Error GoTo Errproc
Dim sFromPath As String
Dim sDestPath As String
Dim k As Integer
'Const sFileType As String = ".pdf"
sFromPath = ActiveWorkbook.Path & "\"
sDestPath = sFromPath & "Archive\"
'validate destination folder
If Len(Dir(sDestPath)) = 0 Then
MsgBox "Destination path does not exist..."
Exit Sub
End If
Dim iRow As Integer
iRow = Range("M" & Rows.Count).End(xlUp).Row
Dim rr As Range, r As Range
Dim FileName As String
Set rr = Range("M5:M" & iRow)
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
For Each r In rr
With objFSO
If Not .FileExists(sDestPath & r.Value) Then
objFSO.MoveFile Source:=sFromPath & r.Value, Destination:=sDestPath
Else
FileName = r.Value
Do Until .FileExists(sDestPath & FileName) = 0
k = k + 1
FileName = Replace(FileName, ".pdf", "-" & k & ".pdf")
Loop
objFSO.MoveFile Source:=sFromPath & FileName, Destination:=sDestPath
End If
End With
Next r
Leave:
Set objFSO = Nothing
On Error GoTo 0
Exit Sub
Errproc:
MsgBox Err.Description, vbCritical
Resume Leave
End Sub