代码末尾的 resume next 在 vba 中代表什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1996256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What happens does resume next at the end of the code stands for in vba?
提问by excel34
Can somebody explain me what this code means ? I guess its if an error occurs go to section ErrHandler, but why is there a resume next at the end and Exit sub inbetween ?
有人可以解释一下这段代码是什么意思吗?我想如果发生错误,请转到 ErrHandler 部分,但是为什么最后有一个 resume next 而其间有 Exit sub 呢?
On Error Goto ErrHandler:
N = 1 / 0 ' cause an error
'
' more code
'
Exit Sub
ErrHandler:
' error handling code
Resume Next
End Sub
I also wrote a short code to get a better understanding. If you run it in VBA excel you will get 4 numbers that pops up in order : 1,2,2,4 I understand the first 2 numbers , but why is the third number 2 and the last one 4 ? btw for this example no error occured .
我还写了一个简短的代码来更好地理解。如果你在 VBA excel 中运行它,你会得到 4 个按顺序弹出的数字: 1,2,2,4 我理解前两个数字,但为什么第三个数字是 2 而最后一个数字是 4 ?顺便说一句,这个例子没有发生错误。
On Error Goto Err:
n = 1
MsgBox n
Err:
n = 2
MsgBox n
Resume Next
MsgBox 4
Resume Next
End Sub
回答by Waleed Al-Balooshi
It has already been said that Resume Next will pick up execution at the point after the error occurred. There is also Resume, which picks up execution starting with the line that caused the error and Resume , which picks up execution at a specified label.
已经说过 Resume Next 将在错误发生后的那一点开始执行。还有 Resume ,它从导致错误的行开始执行,以及 Resume ,它在指定的标签处执行。
So, this is what happens in the code you provided:
因此,这就是您提供的代码中发生的情况:
- N = 1 / 0 raises a divide by zero error
- execution is moved to the ErrHandler label.
- Error handling code will run till it reaches Resume Next.
- Resume next will move execution to the line after N = 1/0. Since you are going back it makes sense that your error handling code might do something like this N = 1, otherwise the rest of the code will try to use N which is uninitialized and you will get another error.
- N = 1 / 0 产生除以零误差
- 执行移动到 ErrHandler 标签。
- 错误处理代码将一直运行,直到到达 Resume Next。
- Resume next 将执行移动到 N = 1/0 之后的行。由于您要返回,因此您的错误处理代码可能会执行类似 N = 1 的操作,否则其余代码将尝试使用未初始化的 N,并且您将收到另一个错误。
The following link provides a simple explanation oerror handling and the three resume statements:
以下链接提供了 oerror 处理和三个 resume 语句的简单说明:
回答by David M
It picks up execution of the method body at the point after where the error occured.
它会在发生错误后的点执行方法体。