为什么VBA出现错误处理代码,当没有错误? [英] Why VBA goes to error handling code when there is no error?

查看:151
本文介绍了为什么VBA出现错误处理代码,当没有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在VBA(Excel)中编写了一些错误处理标签的代码。它工作正常,直到我最近注意到错误处理代码每次都执行,而不仅仅是在发生错误时。有人知道为什么会这样吗?谢谢。



这是一个简单的测试案例,其中两个 msgbox将弹出。

 子示例()
错误GoTo err_handle
MsgBoxOK!
err_handle:
MsgBoxnot OK
End Sub


 子示例()
错误GoTo err_handle
MsgBoxOK!
退出Sub
err_handle:
MsgBoxnot OK
End Sub

查看此处以获得完整的解释。


I have writen some code in VBA (Excel) with error handling labels. It worked fine until I recently notice the error handling code gets executed everytime, not just when an error occurs. Does anybody know why this happens? Thanks.

Here's a trivial test case where both msgboxes would pop up.

Sub example()
    On Error GoTo err_handle
    MsgBox "OK!"
err_handle:
MsgBox "not OK"
End Sub

解决方案

You want to add an Exit Sub to your routine:

Sub example()
    On Error GoTo err_handle
    MsgBox "OK!"
    Exit Sub
    err_handle:
    MsgBox "not OK"
End Sub

Look here for a full explaination.

这篇关于为什么VBA出现错误处理代码,当没有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆