2017-04-20 67 views
-1

我们试图从单个函数返回多个值。函数在VBScript中返回多个值吗?

Sub testing() 
    a = 2 
    b = 5 
    temp = func(a, b) 
    MsgBox temp 
End Sub 

Function func(a, b) 
    'we are validating the multiple returns from the function 
    func = a + b 
    func = a * b 
    func = b/a 
End Function 

回答

2

是的,通过使用Array函数,您可以从单个函数返回多个值。

Function func(a, b) 
    mul = a * b 
    div = a/b 
    add = a + b 
    sub = a - b 
    func = Array(mul, div, add, sub) 
End Function 

然后调用函数,如:

val = func(3,4) 

print val(0) 'will give multiply of 3*4 = 12 
print val(1) 'will give division 
print val(2) 'will give addition 
print val(3) 'will give subtraction. 
3

VBScript函数只返回一个值。如果您分配了多个值的函数名,如你的例子:

func = a + b 
func = a * b 
func = b/a 

只有最后一个值(b/a结果)将被退回。

要让函数返回多个值,需要将值包装到数据结构中并返回该数据结构。这可能是一个数组

func = Array((a+b), (a*b), (b/a)) 

字典

Set d = CreateObject("Scripting.Dictionary") 
d.Add "add", (a+b) 
d.Add "mul", (a*b) 
d.Add "div", (b/a) 

Set func = d 

自定义对象

Class CData 
    Public add, mul, div 
End Class 

... 

Set c = New CData 
c.add = a+b 
c.mul = a*b 
c.div = b/a 

Set func = c 

一个ArrayList

Set a = CreateObject("System.Collections.ArrayList") 
a.Add (a+b) 
a.Add (a*b) 
a.Add (b/a) 

Set func = a 

或一些其它集合。

注意,返回对象,你需要使用Set关键字分配函数的返回值时:

Set temp = func(a, b)