【发布时间】:2015-01-07 06:58:27
【问题描述】:
如何在 VBA 中执行内联错误处理例程?我不想把错误处理程序放在最后。
这是来自CPearson's Error Handling in VBA
Sub testErrHandling()
On Error GoTo ErrHandler:
Debug.print 9 / 0 'divide by zero error
Worksheets("NewSheet").Activate 'missing worksheet error
'more code here
Exit Sub
ErrHandler:
If Err.Number = 9 Then
' sheet does not exist, so create it
Worksheets.Add.Name = "NewSheet"
' go back to the line of code that caused the problem
Resume
End If
End Sub
但我正在寻找更像 VB.net 中的 Try/Catch 块的东西
【问题讨论】:
-
VBA 比 VB.NET 古老得多,并且没有等效的方法来执行 try/catch 块。你可以用非常奇怪的语法和多个
gotos fake 它,但我认为这样做没有任何意义.. -
@vba4all 您应该在下面查看我的答案。我为我的创新感到非常自豪。如果你愿意,你可以说它很奇怪,但历史往往会超越反对者。恕我直言,这当然不是坏代码。
-
我明白你在那里做了什么,但对我来说,
Resume EndTry1与说GoTo <anyLabel>和随机的gotos 没什么不同,都是坏习惯,应该不惜一切代价避免。顺便说一句,您在这里所做的been generally known for years already 可能没有在 SO 上提及。 -
你可以在 VBA 中模拟一个 TRY CTACH 块请看这里stackoverflow.com/q/30991653/4413676