Я внес минимальные изменения в ваш код, чтобы он работал.Тем не менее, я нахожу ваш код запутанным, поэтому я также рекомендовал некоторые дальнейшие изменения.
Мне пришлось поместить ваши образцы данных в диапазон X6: Z10, чтобы первое старое имя файла было в ячейке Y7.
Мне пришлось поместить имя папки, содержащей файлы в ячейке A1.
Надеюсь, причины моих изменений понятны.Спросите, если они не.
Sub pdfrenamefile()
Dim oldfile As String
Dim nwfile As String
Dim rng As Range
Dim fname As Range
' I find your names confusing. For example, You should rename fname to make
' clear that it is a range. You have declared oldname but do now use it.
' You are using methods that require a file system object
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set rng = Range("Y7", Range("Y" & Rows.Count).End(xlUp))
' You use too many different methods of located cells. You use
' rng.Offset(0, c), Cells(r, c) and "AB" & r. Will you understand this
' code in six months? What if you decide to change the position of the
' table of names?
For Each fname In rng
' fname is a range. fname.Value is its value.
If IsEmpty(fname.Value) Or fname.Value = "" Then
Else
' I have replaced "FileFolderExist" by "fso.FileExists".
' "Cells(1, 1)" is acceptable but I prefer "Cells(1, 1).Value"
' which makes absolutely clear you want the value.
If fso.FileExists(Cells(1, 1).Value & fname.Value) Then
' You already have the extension in the worksheet so
' do not need to add ".PDF".
nwfile = fname.Offset(0, 1).Value
' You check the old file exists but not that the new file
' does not exist. I have added another If-Then-Else-End If.
If fso.FileExists(Cells(1, 1) & nwfile) Then
Range("AB" & fname.Row) = nwfile & " already exists"
Else
' The Name statement will not accept non-English letters.
' I have used MoveFile which will accept non-English letters.
' "fname.Value" not "fname" because "fname" is a range.
fso.movefile Cells(1, 1).Value & fname.Value, _
Cells(1, 1).Value & nwfile
' You have nwfile in Offset(0,1). Why duplicate it?
fname.Offset(0, 2) = nwfile
fname.Offset(0, 3) = "Success"
End If
Else
' I have added the old name to the message to make clear
' what has not been found.
Range("AB" & fname.Row) = fname.Value & " not found"
End If
End If
Next fname
End Sub