【发布时间】:2014-08-21 07:17:27
【问题描述】:
我有一个需要帮助的简洁示例。我正在尝试找到一种方法来处理我的错误但保持我的子功能模块化(不需要知道我的其余代码才能正常工作)
在 Excel VBA 中,没有 Try/Catch 功能。 VBA 中有本机函数,如果它们失败则返回错误。我希望使以下示例整洁
Function wrapperForFunction(input As Variant) As Boolean
On Error goto returnTrue
fancyFunctionThatReturnsError(input As Variant)
wrapperForFunction = False
LINE OF CODE THAT SETS ERROR BACK TO WHAT IT WAS BEFORE CHANGING IT TO returnTrue
Return
returnTrue:
wrapperForFunction = True
LINE OF CODE THAT SETS ERROR BACK TO WHAT IT WAS BEFORE CHANGING IT TO returnTrue
End Function
Sub MainProgram()
On Error goto errorHandlerMain
'' do stuff
if wrapperForFunction(input) then 'do stuff
'' do morestuff
if wrapperForFunction(input) then 'do stuff
errorHandlerMain:
'non-erroring cleanup code
End Sub
Sub NestedSub()
On Error goto errorHandlerNestedSub
'' do stuff
if wrapperForFunction(input) then 'do stuff
errorHandlerNestedSub:
'non-erroring cleanup code
End Sub
我要避免的是这种解决方案
Function wrapperForFunction(input As Variant) As Boolean
On Error goto returnTrue
fancyFunctionThatReturnsError(input As Variant)
wrapperForFunction = False
Return
returnTrue:
wrapperForFunction = True
End Function
Sub MainProgram()
On Error goto errorHandlerMain
'' do stuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerMain ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
'' do morestuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerMain ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
errorHandlerMain:
'non-erroring cleanup code
End Sub
Sub NestedSub()
On Error goto errorHandlerNestedSub
'' do stuff
tmp = wrapperForFunction(input) ' <------------ THIS LINE WAS ADDED
On Error goto errorHandlerNestedSub ' <------------ THIS LINE WAS ADDED
if tmp then 'do stuff
errorHandlerNestedSub:
'non-erroring cleanup code
End Sub
有什么建议吗??有没有办法找出当前的“On Error goto x”状态并将其重置为更改之前的状态? 喜欢在
Function foobar()
Dim errorLine As Long: errorLine = CURRENT_ERROR_LINE
On Error goto 40
'do stuff
On Error goto errorLine
Return
40'cleanup code
End Function
【问题讨论】:
-
你可以在 VBA 中模拟一个 TRY CATCH 块请看这里stackoverflow.com/q/30991653/4413676
标签: vba error-handling nested