如何从 VBA 函数返回结果 [英] How to return a result from a VBA function

查看:75
本文介绍了如何从 VBA 函数返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从函数返回结果?

例如:

Public Function test() As Integer
    return 1
End Function

这会导致编译错误.

如何让这个函数返回一个整数?

How do I make this function return an integer?

推荐答案

对于非对象返回类型,您必须将值分配给您的函数名称,如下所示:

For non-object return types, you have to assign the value to the name of your function, like this:

Public Function test() As Integer
    test = 1
End Function

示例用法:

Dim i As Integer
i = test()

如果函数返回一个 Object 类型,那么你必须像这样使用 Set 关键字:

If the function returns an Object type, then you must use the Set keyword like this:

Public Function testRange() As Range
    Set testRange = Range("A1")
End Function

示例用法:

Dim r As Range
Set r = testRange()

请注意,为函数名称分配返回值不会终止函数的执行.如果你想退出函数,那么你需要明确的说Exit Function.例如:

Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function

文档:功能声明

这篇关于如何从 VBA 函数返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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