Mik*_*ike 255 excel vba return function return-value
如何从函数返回结果?
例如:
Public Function test() As Integer
return 1
End Function
Run Code Online (Sandbox Code Playgroud)
这给出了编译错误.
如何让这个函数返回一个整数?
Dan*_*Dan 399
对于非对象返回类型,您必须将值分配给函数的名称,如下所示:
Public Function test() As Integer
test = 1
End Function
Run Code Online (Sandbox Code Playgroud)
用法示例:
Dim i As Integer
i = test()
Run Code Online (Sandbox Code Playgroud)
如果函数返回Object类型,那么必须使用如下Set关键字:
Public Function testRange() As Range
Set testRange = Range("A1")
End Function
Run Code Online (Sandbox Code Playgroud)
用法示例:
Dim r As Range
Set r = testRange()
Run Code Online (Sandbox Code Playgroud)
请注意,为函数名称指定返回值不会终止函数的执行.如果要退出该功能,则需要明确说出Exit Function.例如:
Function test(ByVal justReturnOne As Boolean) As Integer
If justReturnOne Then
test = 1
Exit Function
End If
'more code...
test = 2
End Function
Run Code Online (Sandbox Code Playgroud)
文档:http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx
fro*_*die 84
VBA函数将函数名称本身视为一种变量.因此return,您只需说:而不是使用" "语句,而不是
test = 1
Run Code Online (Sandbox Code Playgroud)
但是请注意,这并没有突破该功能.此语句后的任何代码也将被执行.因此,您可以使用许多赋值语句来分配不同的值test,并且当您到达函数末尾时的值将是返回的值.
Lim*_*awk 36
只是将返回值设置为函数名仍然与Java(或其他)语句不完全相同return,因为在java中,return退出函数,如下所示:
public int test(int x) {
if (x == 1) {
return 1; // exits immediately
}
// still here? return 0 as default.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在VB中,如果未在函数末尾设置返回值,则精确等效项需要两行.因此,在VB中,确切的推论看起来像这样:
Public Function test(ByVal x As Integer) As Integer
If x = 1 Then
test = 1 ' does not exit immediately. You must manually terminate...
Exit Function ' to exit
End If
' Still here? return 0 as default.
test = 0
' no need for an Exit Function because we're about to exit anyway.
End Function
Run Code Online (Sandbox Code Playgroud)
既然如此,那么知道你可以像使用方法中的任何其他变量一样使用return变量也是很好的.像这样:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test <> 1 Then ' Test the currently set return value
test = 0 ' Reset the return value to a *new* value
End If
End Function
Run Code Online (Sandbox Code Playgroud)
或者,返回变量如何工作的极端例子(但不一定是你应该如何实际编码的一个很好的例子) - 那个会让你夜不能寐的例子:
Public Function test(ByVal x As Integer) As Integer
test = x ' <-- set the return value
If test > 0 Then
' RECURSIVE CALL...WITH THE RETURN VALUE AS AN ARGUMENT,
' AND THE RESULT RESETTING THE RETURN VALUE.
test = test(test - 1)
End If
End Function
Run Code Online (Sandbox Code Playgroud)