重命名文件时忽略错误58

时间:2017-12-22 11:40:05

标签: vba ms-access access-vba

我有一个小型的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

2 个答案:

答案 0 :(得分:3)

如果您某些您可以忽略该错误,那么您可以使用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

答案 1 :(得分:0)

我想到了两个特殊的解决方案。第一个是检查现有文件的内联逻辑,并跳过该项,第二个是在错误处理程序中放置一个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