通过一些研究和尝试,我发现了这个基本的VBA,它可以帮助我重命名大量的文件附件。我已经重命名了几十个附件,但我遇到了运行时错误'53: File Not File‘。有没有办法修改VBA以跳过找不到的文件名?
Sub RenameFiles()
Const strPath = "C:\Documents and Settings\User\My Documents\FolderName\"
Dim r As Long
Dim n As Long
n = Cells(Rows.Count, 1).End(xlUp).Row
For r = 2 To n
Name strPath & Cells(r, 1) As strPath & Cells(r, 2)
Next r
End Sub
发布于 2013-06-26 15:25:58
使用以下语句禁用错误处理:
On Error Resume Next
要再次启用错误处理,必须使用以下语句:
On Error Goto 0
这是一个很好的做法,禁用错误处理只对你真正想跳过错误的语句。另一方面,启用和禁用错误处理可能会减慢代码的运行速度。在这种情况下,你可以把它放在循环的周围。
On Error Resume Next
For r = 2 To n
Name strPath & Cells(r, 1) As strPath & Cells(r, 2)
Next r
On Error Goto 0
发布于 2013-06-26 15:12:15
在您的子例程的顶部添加以下行:
On Error Resume Next
这条语句完全按照它所说的做,它忽略了错误并继续下一行代码。
在使用此语句时,您需要使用注意,因为它不能修复错误。对于您当前的问题,这应该没问题,但在许多其他问题中,您需要处理错误而不是忽略它。
获取基础知识的一个很好的资源是Error Handling in VBA。
如果您想了解有关Excel VBA的更多信息,brettdj对What is the best way to master VBA macros的回答是一个很好的起点。
要查看On Error Resume Next
或On Error GoTo 0
对错误的影响,请在VBA编辑器中逐步执行以下操作:
Sub ExcelVBAErrorDemo()
Dim forceError As Integer
' ignore errors
On Error Resume Next
' cause an error
forceError = 1 / 0
' the error was ignored, and the integer variable will
' display its default value
MsgBox "Our forceError variable = " & forceError
' turn default error handling behavior back on
On Error GoTo 0
' now we'll get a run-time error
forceError = 1 / 0
End Sub
发布于 2013-06-26 15:42:26
(在我看来)比On Error Resume Next
更好的是检查特定的/预期的错误并适当地处理它们。在这种情况下,您可以检查文件名是否有效,如果无效,则跳过Name
分配。
使用Dir()
函数检查它是否是有效的文件名:
Sub RenameFiles()
Const strPath = "C:\Documents and Settings\User\My Documents\FolderName\"
Dim sFile as String
Dim r As Long
Dim n As Long
n = Cells(Rows.Count, 1).End(xlUp).Row
For r = 2 To n
sFile = strPath & Cells(r,1)
If Not Dir(sFile) = vbNullString Then
Name sFile As strPath & Cells(r, 2)
End If
Next r
End Sub
https://stackoverflow.com/questions/17321504
复制相似问题