【发布时间】:2022-06-13 13:11:24
【问题描述】:
在 VBA 中,错误处理由 on error 语句完成。
我想暂时更改错误处理,然后再回到以前的行为。如何检查当前的错误处理并将其存储在变量中(我在引用中找不到任何内容)?
'set the error handling to s.th. "on error... "
'some code with the regular error handling
'change the error handling to "on error ..." (regardless of what it was before)
'some code with the new error handling
'change back to the previous error handling
'some code with the regular error handling
背景:我需要对 Variant 数组进行is nothing 检查以排除使用空对象索引,但将is nothing 应用于包含值的数组索引会引发异常,所以我暂时想更改对on error resume next 的错误处理。最终使用不同的方法解决了这个问题,但我仍然想知道我是否可以在运行时以某种方式确定当前的错误处理Here's the question and answer to my original problem。
编辑:我知道我可以手动检查我以前的代码以找出使用了哪种类型的错误处理。但是我想避免这种情况(以节省时间)。
我想作为一种解决方法,我可以设置一个带有状态的附加变量,然后我可以检查当前状态,尽管这会导致相当多的开销。像这样的:
Dim errorHandling as String
errorHandling = "resumeNext"
on error resume next
'some code
'changing the error handling temp.
'some other code
'changing the error handling to it's previous state
if errorhandling = "resumeNext" then
On Error Resume Next
elseif errorhandling = "GoToErrorhandler" then
On Error GoTo errorhandler
End If
'Rest of the code
【问题讨论】:
-
您需要将代码添加到此问题中。另外,至少,添加您填充数组的方式。当你声明一个数组
As Variant时,每个元素都被赋值为Empty,而不是Nothing,因此你需要做类似If IsEmpty(MyArray(i)) Then或If Not IsEmpty(MyArray(i)) Then的操作。你为什么不分享完整的代码,这样你就可以看到它是如何应用的。经验法则是使用错误捕获(处理)作为“最后的手段”,即当没有其他(简单)方法时。 -
@VBasic2008 这个问题与数组无关,我只是想暂时更改错误处理(无需手动检查之前的内容)。
-
你为什么不解释一下
temporarily change the error handling是什么意思?没有解释,对我来说没有任何意义。也许在您的帖子中添加一些代码或伪代码。 -
抱歉我的编辑速度不够快...
标签: vba error-handling