我正在运行下面的代码作为更改大批图像名称的方法。
但是,只要找不到文件中的图像名称(可能是由于重复,意外删除或手指疾病),就会出错。
有没有办法让脚本在发生这种情况时继续运行,或者让它突出显示罪魁祸首,以便它可以删除(或两者都哈哈)?
提前致谢!!并且感谢原始代码,从这里得到它:)
代码如下。
Sub RenameImages()
'
' RenameImages Macro
'
' Keyboard Shortcut: Ctrl+Shift+I
'
Dim Source As Range
Dim OldFile As String
Dim NewFile As String
Set Source = Cells(1, 1).CurrentRegion
For Row = 1 To Source.Rows.Count
OldFile = ActiveSheet.Cells(Row, 1)
NewFile = ActiveSheet.Cells(Row, 2)
' rename files
Name OldFile As NewFile
Next
End Sub
答案 0 :(得分:1)
您有多种方法可以处理此问题,您可以使用FileExists()函数,如下所示:
Dim fso As Object
Dim MyPath As String
Set fso = CreateObject("Scripting.FileSystemObject")
MyPath = "C:\myFile.txt"
If fso.FileExists(MyPath) = False Then
MsgBox MyPath & " doesn't exist"
Else
'Rename your file
End If
处理此问题的另一种方法是使用ErrorHandler:
Sub RenameImages()
On Error Goto ErrorHandling
'
' RenameImages Macro
'
' Keyboard Shortcut: Ctrl+Shift+I
'
Dim Source As Range
Dim OldFile As String
Dim NewFile As String
Set Source = Cells(1, 1).CurrentRegion
For Row = 1 To Source.Rows.Count
OldFile = ActiveSheet.Cells(Row, 1)
NewFile = ActiveSheet.Cells(Row, 2)
' rename files
Name OldFile As NewFile
Next
Exit Sub
ErrorHandling:
Debug.Print "File doesn't exist: " & OldFile
Resume Next
End Sub
答案 1 :(得分:0)
在FOR Row = 1...
行之前,行On error resume next
应该可以解决问题
在Next
之后的行上,请使用On error goto 0