VBA:On Error Resume Next 工作多长时间? [英] VBA: How long does On Error Resume Next work?

查看:22
本文介绍了VBA:On Error Resume Next 工作多长时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读如何使用 On Error Resume Next 并且我正在尝试弄清楚该行将应用于程序多长时间.在微软的网站上,我发现了这样一句话:An 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 ErrorGoTo 行被认为是糟糕的编码.是否有一个 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

  1. 您知道错误发生的原因.

  1. 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:On Error Resume Next 工作多长时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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