我在Vba中使用错误处理程序,并希望在我的代码中使用错误处理程序,正如许多专家建议的那样。
Sub test()
For i =1 to 100
On Error GoTo ErrHand:
Filename=Dir()
Folder=
Workbooks.open(Folder & Filename)
Label1:
Code
Code
Close the file
ErrHand:
Application.GetOpenFilename()
GoTo Label1
Next i
End Sub
我发现以正常方式运行代码存在困难。我尝试写一个文件,如果它失败了,我调用错误处理程序并提示选择一个文件然后我关闭文件并为下一个文件做同样的事情。我面临的一个困难是打开的文件永远不会关闭。提前致谢。
答案 0 :(得分:2)
除了Jeeped的出色建议:
Sub test()
On Error GoTo ErrHand:
For i =1 to 100
Filename=Dir()
set Folder= Workbooks.open(Folder & Filename)
'Label1:
Code
Code
folder.Close 'based on using 'folder', above
next
exit sub 'if you don't do this, code execution will go right into your error handler
ErrHand:
if err.Number = <something>
Application.GetOpenFilename()
'GoTo Label1
Resume Next 'this is a simpler version, and doesn't require a label and another GoTo
'skips the line of code that errored, continues with the next line
elseif err.number = <something else>
'...
Resume 'allows you to retry the same statement after making some changes
endif
'Next i
End Sub