如何使用On Error GoTo?

我导致相信,vba的IDE不允许正确的打破错误。 我问了一个关于如何识别运行时错误的问题:

我如何打破错误?

解决scheme/解决方法似乎是使用On Error GoTo ErrorHandler或类似的。 我正在努力工作,但没有取得太大的成功。

根据Microsoft On Error GoTo将发送运行时错误时发送给区域的指定代码( https://msdn.microsoft.com/en-us/library/5hsw66as.aspx )。 根据我的经验,这不是整个故事。 这个问题是关于如何实际解决scheme的工作。

所以我有以下function:

 Function generateTimeseries() As Variant On Error GoTo ErrorHandler Dim currentArray As Range currentArray = Selection.Range ' this doesn't work - I don't care why generateTimeseries = currentArray.Rows Return ErrorHandler: Debug.Assert False Resume ' break here if you want to catch errors End Function 

这个函数永远不会进入ErrorHandler代码。 相反,它落在Selection.Range ,函数只是返回#VALUE 。 我其实不在意为什么这会打破,我只是想知道如何让IDE告诉我,它实际上倒在了那一行,没有我手动跳过代码。

我只是testing和你的error handling程序的作品,它正确地打破了

 Debug.Assert False 

– >检查debugging器选项。

但是,这不是一个正确的方法来处理vBA中的错误,因为如果你编译你的应用程序,并忘记适应这样的error handling程序,当用户在程序中遇到错误时,应用程序将陷入无限循环。

在大多数情况下,你必须抛出一个msgbox让用户知道发生了错误,并终止当前的过程。 唯一不适用的情况是当你做了一些可能引发错误的事情,但是你知道它并故意避开这个错误。 这是一个罕见的情况。

我从来没有使用Assert方法,这是我如何处理我的错误在每个程序

 Function generateTimeseries() As Variant On Error GoTo ErrorHandler Dim currentArray As Range currentArray = Selection.Range ' this doesn't work - I don't care why generateTimeseries = currentArray.Rows Exit_Function: Exit Function ErrorHandler: MsgBox Err.Description, vbCritical, "Error " & Err.Number Resume Exit_Function ' breakpoint here if you want examine the code after error, otherwhise it terminates the function Resume ' Once the code breaks on the above line, move to this instruction and F8 to return to the statement in error End Function 

我已经启用了function“在所有错误打破”在早先尝试打破所有错误。

我通过Tools->Options->General来取消closuresBreak on All ErrorsBreak on Unhandled Errors

事实certificate, Break on All Errors是Windows的“打破一些错误,但只是返回垃圾,如果这是一个UDF错误”。