using On Error Resume Next to skip any error on the below code,But it dose not work.
I got error File not found on the second VBA name command.
I know that code can be modified to check existence of the file before rename.
I need to know why On Error Resume Next did not skip that error.
Thanks for your helping.
Sub Name_Test()
On Error GoTo Pause
Dim oldName As String: oldName = "C:\Users\Waleed\Desktop\Test.txt"
Dim newName As String: newName = "C:\Users\Waleed\Desktop\Done.txt"
Name oldName As newName
Pause:
On Error Resume Next
Application.Wait Now TimeValue("00:00:01")
Name oldName As newName
ThisWorkbook.Save
End Sub
CodePudding user response:
Please, try this updated code. It uses On Error GoTo -1 to clear the previous error from memory:
Sub Name_Test()
On Error GoTo Pause
Dim oldName As String: oldName = "C:\Users\Waleed\Desktop\Test.txt"
Dim newName As String: newName = "C:\Users\Waleed\Desktop\Done.txt"
Name oldName As newName
Pause:
Application.Wait Now TimeValue("00:00:01")
On Error GoTo -1 'it clears the previous error from memory!
On Error Resume Next
Name oldName As newName
If Err.Number <> 0 Then Stop 'it has been caught, but no error has been raised, anymore...
'ThisWorkbook.Save
End Sub
"Note: Err.Clear is different from On Error Goto -1. Err.Clear only clears the error description and the error number. In the case of On Error GoTo label, it doesn’t completely reset it (from memory). This means that if there is another instance of error in the same code, you will not be able to handle it before resetting, which can be done with On Error Goto -1 and not using Err.Clear"
I found the above note (or something with a similar meaning) some years before, when searched to clarify this aspect...
