在我自己的 vba 函数中获得没有 gosub 的回报 [英] Getting return without gosub in my own function in vba

查看:69
本文介绍了在我自己的 vba 函数中获得没有 gosub 的回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在与 vba 作斗争,但令人惊讶的是它并没有变得更好.我编写了以下代码,以便我可以为对象使用特殊的比较运算符.

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.

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

我传入的对象 v 目前是 Nothing,所以我预计结果是一个微不足道的 False.令人惊讶的是,我收到了一个错误 Return without gosub.知道为什么会这样吗?

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?

推荐答案

删除 Return 语句!

在 VBA 中,您使用 myEquals = ... 行设置返回值.

In VBA, you set the return value with the line 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

或者,使用这个:

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 如果您想在代码中使用直接跳转,即构建意大利面条式代码,则是一个古老的遗物!请参阅帮助文件中的此示例:

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:

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.

这篇关于在我自己的 vba 函数中获得没有 gosub 的回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆