在我自己的 vba 函数中获得没有 gosub 的回报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15225945/
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
Getting return without gosub in my own function in vba
提问by DRF
I've been battling with vba for a bit and surprisingly it's not getting much better. I have written the following code so I can have a special comparison operator for an object.
我一直在与 vba 作斗争,但令人惊讶的是它并没有变得更好。我编写了以下代码,以便我可以为对象使用特殊的比较运算符。
Public Function myEquals(v As CCtypestore) As Boolean
If v Is Nothing Then
myEquals = False
Return
End If
If Me.Acronym = v.Acronym Then
myEquals = True
Return
End If
myEquals = False
Return
End Function
The object v I'm passing in is Nothing at the moment so I would have sort of expected the result to be a trivial False. Surprisingly instead I'm getting an error Return without gosub. Any clue why that might be?
我传入的对象 v 目前是 Nothing ,所以我有点期望结果是一个微不足道的 False 。令人惊讶的是,我收到了一个错误 Return without gosub。知道为什么会这样吗?
回答by Peter Albert
Delete the Return
statements!
删除Return
声明!
In VBA, you set the return value with the line myEquals = ...
.
在 VBA 中,您可以使用行设置返回值myEquals = ...
。
All in all, you can reduce your function to the following code:
总而言之,您可以将函数简化为以下代码:
Public Function myEquals(v As CCtypestore) As Boolean
If Not v Is Nothing Then
myEquals = (Me.Acronym = v.Acronym)
End If
End Function
Alternatively, use this:
或者,使用这个:
Public Function myEquals(v As CCtypestore) As Boolean
On Error Goto ErrorHandler
myEquals = (Me.Acronym = v.Acronym)
Exit Function
ErrorHandler:
myEquals = False
End Function
Return
is an old relic if you want to work with direct jumps in the code, i.e. build spaghetti code! See this example from the help file:
Return
如果您想在代码中使用直接跳转,即构建意大利面条式代码,这是一个古老的遗物!请参阅帮助文件中的此示例:
Sub GosubDemo()
Dim Num
' Solicit a number from the user.
Num = InputBox("Enter a positive number to be divided by 2.")
' Only use routine if user enters a positive number.
If Num > 0 Then GoSub MyRoutine
Debug.Print Num
Exit Sub ' Use Exit to prevent an error.
MyRoutine:
Num = Num/2 ' Perform the division.
Return ' Return control to statement.
End Sub ' following the GoSub statement.
回答by Patrick Honorez
Use Exit Function
instead of Return
.
使用Exit Function
代替Return
。
You can also avoid those Exit Function
by using a construction like
你也可以Exit Function
通过使用像这样的结构来 避免这些
If .... Then
'some code
ElseIf...Then
'some other code
ElseIf...Then
'etc
Else
'final
End if