是Resume后总是需要On Error处理?是否会因为压缩Resume下面示例中的行而导致堆栈错误跳过它?
Sub MySub
on error goto Hell
DoThis
DoThat
Otherstuff
Adios:
Exit Sub
Hell:
MsgBox Err.Description, vbCritical, "Error " & Err.Number
Resume Adios 'is this line required ?
Exit Sub
Run Code Online (Sandbox Code Playgroud)
Resume语句指示VBA在代码中的指定点继续执行.您只能在错误处理块中使用Resume; 任何其他用途都会导致错误.此外,除了退出过程之外,Resume是唯一的方法,以摆脱错误处理块.不要使用Goto语句将代码执行从错误处理块中引出.这样做会导致错误处理程序出现奇怪问题.
Resume语句采用三种语法形式:
Resume
Resume Next
Resume <label>
Run Code Online (Sandbox Code Playgroud)
单独使用,Resume会导致执行在导致错误的代码行中恢复.在这种情况下,您必须确保错误处理块修复了导致初始错误的问题.否则,您的代码将进入无限循环,在导致错误的代码行和错误处理块之间跳转.以下代码尝试激活不存在的工作表.这会导致错误(9 - 下标超出范围),并且代码跳转到创建工作表的错误处理块,更正问题,并在导致错误的代码行继续执行.
On Error GoTo ErrHandler:
Worksheets("NewSheet").Activate
Exit Sub
ErrHandler:
If Err.Number = 9 Then
' sheet does not exist, so create it
Worksheets.Add.Name = "NewSheet"
' go back to the line of code that caused the problem
Resume
End If
Run Code Online (Sandbox Code Playgroud)
Resume的第二种形式是Resume Next.这导致代码执行在紧接导致错误的行之后的行处继续.尝试设置N的值时,以下代码会导致错误(11 - 除以零).错误处理块将1赋值给变量N,然后导致执行在导致错误的语句之后的语句处继续执行.
On Error GoTo ErrHandler:
N = 1 / 0
Debug.Print N
Exit Sub
ErrHandler:
N = 1
' go back to the line following the error
Resume Next
Run Code Online (Sandbox Code Playgroud)
简历的第三种形式是简历<label>:.这会导致代码执行在行标签处恢复.这允许您在发生错误时跳过一段代码.例如,
On Error GoTo ErrHandler:
N = 1 / 0
code that is skipped if an error occurs
Label1:
more code to execute
Exit Sub
ErrHandler:
go back to the line at Label1:
Resume Label1:
Run Code Online (Sandbox Code Playgroud)
所有形式的Resume都会清除或重置Err对象.
发现这个
http://www.cpearson.com/excel/errorhandling.htm