从函数中返回多个值的方法
There are several ways to return multiple values from functions. In this topic, we’re going to look over the 5 most common techniques to pass 2 or more values from functions. The 5 techniques are:
1、Returning variables in Global scope
2、Returning a Collection
3、Returning Arrays
4、Using Concatenated Strings
5、Passing through the use of ByRef
Returning variables in Global scope
This can be achieved by declaring the variables outside the scope of the function. Here, we don’t need to pass the values through the function; but we can simply manipulate them within the function’s scope. Please note that if the same string is declared within the function, it loses its global scope – as it becomes local to the function. These variables can come from a function library or from the test script as long as they are outside the scope of the calling method. Code snippet:
Returning a Collection
Another way to pass multiple values from a function is through the using of creating and passing Collections. We can use a collection object to store multiple values as keys/items. Code snippet:
Public Function PassValues(ByVal Num_1, ByVal Num_2)Set oDict = CreateObject( "Scripting.Dictionary" )With oDict.Add "Num_1", Num_1/4.Add "Num_2", Num_2/2End WithSet PassValues = oDict End FunctionSet colNumbers = PassValues(40,80)MsgBox "intNumber_1 = " & colNumbers.Item("Num_1") &_vbLf & "intNumber_2 = " & colNumbers.Item("Num_2")Returning Arrays
This is quite a common technique. Each element in the array stores a variable that is then passed through the function. Code snippet:
Public Function PassValues(ByVal Num_1, ByVal Num_2)Dim arrArray: ReDim arrArray(2)arrArray(0) = Num_1/4arrArray(1) = Num_2/2PassValues = arrArray End FunctionarrNew = PassValues(40,80)MsgBox "intNumber_1 = " & arrNew(0) &_vbLf & "intNumber_2 = " & arrNew(1)Concatenated Strings
I have seen the usage of this technique almost as frequently as the use of arrays. Here, two or more concatenated numbers/strings can be passed through the function with the help of a delimiter. Code snippet:
Public Function PassValues(ByVal Num_1, ByVal Num_2)Num_1 = Num_1/4Num_2 = Num_2/2PassValues = Num_1 & "," & Num_2 End FunctionsNum = PassValues(40,80)MsgBox "intNumber_1 = " & Split(sNum, ",")(0) &_vbLf & "intNumber_2 = " & Split(sNum, ",")(1)Using ByRef to Pass Multiple Values
Please refer to the article?Passing Parameters ByRef and ByVal?for a detailed explanation of this technique. It can be used to pass multiple values in the following manner:
Dim intNumber_1: intNumber_1 = 40 Dim intNumber_2: intNumber_2 = 80Public Sub PassValues(ByRef Num_1, ByRef Num_2)Num_1 = Num_1/4Num_2 = Num_2/2 End SubPassValues intNumber_1, intNumber_2MsgBox "intNumber_1 = " & intNumber_1 &_vbLf & "intNumber_2 = " & intNumber_2
總結
以上是生活随笔為你收集整理的从函数中返回多个值的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在51单片机上使用递归的注意事项
- 下一篇: 通达信版弘历软件指标_通达信获利分析仿弘