重命名文件时忽略错误58
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了重命名文件时忽略错误58相关的知识,希望对你有一定的参考价值。
我有一个小的Access程序,它从查询中查找文件名(“qryImagesToRename”),经历一个循环并重命名它们。但是,如果已经存在具有相同名称的图像,Access希望将其重命名为,我会收到
错误58 - 文件已存在
如何忽略此错误并继续循环?这是我的代码:
Private Sub Command10_Click()
On Error GoTo Command10_Click_Error
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim strSQL As String
DoCmd.Hourglass True
Set db = CurrentDb
strSQL = "select * from qryImagesToRename"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
Name rs.Fields("From").Value As rs.Fields("To").Value
rs.MoveNext
Loop
DoCmd.Hourglass False
MsgBox "All matching files renamed"
On Error GoTo 0
Exit Sub
Command10_Click_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Command10_Click of VBA Document Form_frmRename - Please take a screenshot and email xxxxxx@xxxxxxx.com"
End Sub
答案
如果您确定可以忽略该错误,那么您可以使用On Error Resume Next
忽略它并继续处理。确保尽快添加On Error Goto 0
,以恢复正常的错误处理。
On Error Resume Next
Do While Not rs.EOF
Name rs.Fields("From").Value As rs.Fields("To").Value
rs.MoveNext
Loop
On Error GoTo 0
这通常是一种糟糕的做法,但如果对行为有确定性,则可以使用。
更好的做法是使用Dir
(或FileSystemObject
)检查文件是否已存在并跳过它。讨论了here
另一答案
我想到了两个特殊的解决方案。第一个是检查现有文件的内联逻辑,并跳过该项,第二个是在错误处理程序中放置一个case语句。我已经概述了下面的代码,有两个选项。我希望它有所帮助。
Private Sub Command10_Click()
On Error GoTo Command10_Click_Error
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim strSQL As String
Dim fso as New FileSystemObject
DoCmd.Hourglass True
Set db = CurrentDb
strSQL = "select * from qryImagesToRename"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF 'if you want to use the logic inline, use the check below
If fso.fileexists(rs.Fields("To").value) = false Then
Name rs.Fields("From").Value As rs.Fields("To").Value
End If
NextRecord: 'if you want to use the goto statement, use this
rs.MoveNext
Loop
DoCmd.Hourglass False
MsgBox "All matching files renamed"
On Error GoTo 0
Exit Sub
Command10_Click_Error:
Select case Err.number
Case 58
GoTo NextRecord
Case Else
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Command10_Click of VBA Document Form_frmRename - Please take a screenshot and email xxxxxx@xxxxxxx.com"
End select
End Sub
以上是关于重命名文件时忽略错误58的主要内容,如果未能解决你的问题,请参考以下文章