Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

excel - 如何从VBA函数返回结果(How to return a result from a VBA function)

How do I return a result from a function?

(如何从函数返回结果?)

For example:

(例如:)

Public Function test() As Integer
    return 1
End Function

This gives a compile error.

(这给出了编译错误。)

How do I make this function return an integer?

(如何使此函数返回整数?)

  ask by Mike translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Example usage:

(用法示例:)

Dim i As Integer
i = test()

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

(如果函数返回对象类型,则必须使用Set关键字,如下所示:)

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

Example usage:

(用法示例:)

Dim r As Range
Set r = testRange()

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 .

(如果要退出该功能,则需要明确说出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

Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx

(文档: http : //msdn.microsoft.com/zh-cn/library/office/gg264233%28v=office.14%29.aspx)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...