vba VBA出错时如何从函数返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4553814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return from a function in case of error in VBA
提问by Ashish Gupta
I am new to VBA and want to return from a function when I see an error. Not able to do so. Any pointers?
我是 VBA 新手,想在看到错误时从函数返回。不能这样做。任何指针?
Function GetEditboxValue(control As IRibbonControl, text As String) As String
If Not IsMissing(text) Then
If Not IsNumeric(text) Then
MsgBox "Please enter numeric value only."
' I WANT TO RETURN HERE
End If
End If
If control.id = "xyz" Then
spaceAboveTable = text
End If
End Function
回答by Sarfraz
You need to put EXIT FUNCTIONthere to get out of further execution:
你需要把它放在EXIT FUNCTION那里以退出进一步的执行:
Function GetEditboxValue(control As IRibbonControl, text As String) As String
If Not IsMissing(text) Then
If Not IsNumeric(text) Then
MsgBox "Please enter numeric value only."
EXIT FUNCTION
End If
End If
If control.id = "xyz" Then
spaceAboveTable = text
End If
End Function
回答by Ashish Gupta
In a generalized sense (I'm not actually saying anything that hasn't already been said):
从广义上讲(我实际上并不是在说任何尚未说过的话):
Function Foo(inputVar As Double) As Double
On Error GoTo ErrorHandler
' Code assigning something to returnValue and defaultOutput
Foo = returnValue
Exit Function
ErrorHandler:
Foo = defaultOutput
End Function
No reason it has to be Double, of course.
当然,没有理由必须是 Double。
(Edited because I had a second "Exit Function" instead of "End Function.")
(编辑是因为我有第二个“退出函数”而不是“结束函数”。)
回答by Alex P
You can use Exit Functionafter your MsgBoxstatement
你可以Exit Function在你的MsgBox声明之后使用
回答by mwolfe02
Another option is to explicitly raise an error using Err.Raise. Since you have no error handler within this function (ie, no On Error ...line) the error will be propagated up through the call stack until it runs into an error handler.
另一种选择是使用Err.Raise. 由于您在此函数中没有错误处理程序(即,没有On Error ...行),错误将通过调用堆栈向上传播,直到它运行到错误处理程序中。

