我有一个循环来处理文件夹的每个文件。如果文件已损坏且无法打开,我想: - 向用户显示错误消息 - 停止执行剩余的代码 - 循环到下一个文件
问题是,如果在循环开始时无法打开文件,那么仍会有很多代码会执行,这会引发其他错误。我无法退出循环,因为这意味着并非所有文件都会被处理,我无法继续执行代码。请参阅下面的代码部分。
Set fso = CreateObject("Scripting.FileSystemObject")
For each objFile in fso.GetFolder(".").Files
If lCase(fso.GetExtensionName(objFile)) = srcExtName Then
Set app = GetNewAppInstance (Program)
Set fileHandle = GetNewFileHandler(app)
On Error Resume Next
Set objOpenFile = fileHandle.Open(objFile.path)
If err.number <> 0 Then
next
MsgBox "The file " & objFile.name & " cannot be opened. Please verify that the file is not corrupted or locked." & vbNewLine & "The file will be skipped."
Set fileHandle = nothing : app.Quit : Set app = nothing
<<< How can I jump to the next file from here ? >>>
End If
On error goto 0
strSrcPath = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "._temp")
objOpenFile.SaveAs strSrcPath, tmpExtNum
objOpenFile.Close
Set objOpenFile = nothing
Set fileHandle = nothing
app.Quit : Set app = nothing
Set app = GetNewAppInstance (Program)
Set fileHandle = GetNewFileHandler(app)
Set objOpenFile = fileHandle.Open(strSrcPath)
strTgtPath = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "." & srcExtName)
objOpenFile.SaveAs strTgtPath, srcExtNum
objOpenFile.Close
fso.DeleteFile(strSrcPath)
Set objOpenFile = nothing
Set fileHandle = nothing
app.Quit : Set app = nothing
End If
Next
End Sub
谢谢!
答案 0 :(得分:3)
试试这个:
Set fso = CreateObject("Scripting.FileSystemObject")
For each objFile in fso.GetFolder(".").Files
If lCase(fso.GetExtensionName(objFile)) = srcExtName Then
Set app = GetNewAppInstance (Program)
Set fileHandle = GetNewFileHandler(app)
On Error Resume Next
Set objOpenFile = fileHandle.Open(objFile.path)
If err.number <> 0 Then
MsgBox "The file " & objFile.name & " cannot be opened. Please verify that the file is not corrupted or locked." & vbNewLine & "The file will be skipped."
Set fileHandle = nothing : app.Quit : Set app = nothing
Else
strSrcPath = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "._temp")
objOpenFile.SaveAs strSrcPath, tmpExtNum
objOpenFile.Close
Set objOpenFile = nothing
Set fileHandle = nothing
app.Quit : Set app = nothing
Set app = GetNewAppInstance (Program)
Set fileHandle = GetNewFileHandler(app)
Set objOpenFile = fileHandle.Open(strSrcPath)
strTgtPath = fso.BuildPath(objOpenFile.path, fso.GetBaseName(objOpenFile.name) & "." & srcExtName)
objOpenFile.SaveAs strTgtPath, srcExtNum
objOpenFile.Close
fso.DeleteFile(strSrcPath)
Set objOpenFile = nothing
Set fileHandle = nothing
app.Quit : Set app = nothing
End If
On error goto 0
End If
Next
我已将代码的“其余”移动到if语句的else块中,因此只有在没有错误时才会执行。