我有一个整洁的例子,我需要帮助。我试图找到一种方法来处理我的错误,但保持我的子功能模块化(不需要知道我的代码的其余部分是否正常工作)VBA子功能错误处理
在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块请看这里 http://stackoverflow.com/q/30991653/4413676 – HarveyFrench