VBA:“错误恢复下一个"继续工作多长时间? [英] VBA: How long does On Error Resume Next work?
问题描述
我正在阅读如何使用On Error Resume Next
,并且试图弄清楚该行将在该程序上应用多长时间.在Microsoft网站上,我发现了这样一句话:在调用另一个过程时,On Error Resume Next语句变为非活动状态."这到底是什么意思?什么是程序?
I'm reading up on how to use On Error Resume Next
and I'm trying to figure out how long that line will apply to the program. On the Microsoft site, I found this sentence: "An On Error Resume Next statement becomes inactive when another procedure is called." What exactly does this mean? What is considered to be a procedure?
我问是因为我在程序中使用了该行,但我不希望它Resume Next
发生的所有运行时错误,仅是下一行中的明显错误.
I ask because I'm using the line in my program, but I don't want it to Resume Next
all the runtime errors which occur, just the obvious one on the next line.
代码:
Dim zRange As Range
Call FilterTableFor(fieldNameColumn, Array("baseunitprice", "burden", "MTLBURRATE", "PurPoint", "Vendornum"))
On Error Resume Next
Set zRange = commentsColumnRange.SpecialCells(xlCellTypeVisible)
zRange.Formula = "target"
Call FilterTableFor(fieldNameColumn)
我还发现(并且有一段时间了)On Error
或GoTo
行被认为是不良编码.我可以将Try-Catch
用于这样的行吗?
I've also found (and known for a while) that On Error
or GoTo
lines are considered poor coding. Is there a Try-Catch
which I can use for a line like this?
我在想这样的事情:
Dim zRange As Range
Call FilterTableFor(fieldNameColumn, Array("baseunitprice", "burden", "MTLBURRATE", "PurPoint", "Vendornum"))
Try
Set zRange = commentsColumnRange.SpecialCells(xlCellTypeVisible)
zRange.Formula = "target"
Catch()
Call FilterTableFor(fieldNameColumn)
在我什至不做任何事情的地方,因为我不需要这样做.
Where I don't even do anything with it, as I don't feel a need to.
感谢您的时间.
推荐答案
在以下情况下,您只想使用"On Error Resume Next"
You only want to use "On Error Resume Next" when
-
您知道为什么会发生错误.
You know why the error occurs.
您知道它不会影响代码的其他部分.
You know that it will not affect other parts of the code.
在发生错误的代码后立即使用"On Error Goto 0".
You use "On Error Goto 0" immediately after the code where the error occurs.
话虽如此,几乎不要使用它.您应该弄清楚为什么会发生错误,并通过代码进行处理.
Having said that, you should almost NEVER use it. You should figure out why the error occurs and code to handle it.
网站所说的是,一旦您退出了调用它的子函数或子函数,下一个简历将不再起作用,并且您的错误将按预期出现.
What the website is saying is that once your are out of the sub or function that called it the resume next will no longer be in affect and your errors will raise as they should.
更好的选择是以这种方式使用goto.但是有些人对此几乎不满意.
A better alternative is to use goto in this fashion. But some people frown on this almost as much.
sub SomeSub()
On Error Goto TestFailed
'Some code
'Some code
'Some code
Exit sub
TestFailed:
'Some code here to alert you to and/or handle the fallout of the error.
End sub
这篇关于VBA:“错误恢复下一个"继续工作多长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!