【问题标题】:Ignore error 58 when renaming files重命名文件时忽略错误 58
【发布时间】:2018-06-05 01:44:09
【问题描述】:

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

【问题讨论】:

  • 不要忽视它,这是可怕的做法。而是先使用Dir(filename)函数检查它是否存在,如果存在,以某种方式修改新名称。

标签: ms-access vba


【解决方案1】:

我想到了两个特定的解决方案。第一个是检查现有文件并跳过该项目的内联逻辑,第二个是将 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      

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 1970-01-01
      • 2016-05-03
      • 1970-01-01
      • 2012-03-27
      • 2023-02-11
      • 2018-06-20
      • 1970-01-01
      • 2018-08-31
      相关资源
      最近更新 更多