-1

We are trying to return multiple values from a single function.

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
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
jitendra gupta
  • 47
  • 2
  • 11

2 Answers2

3

VBScript functions return just a single value. If you assign multiple values to the function name as in your example:

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

only the last value (the result of b / a) will be returned.

To have a function return multiple values you need to wrap the values in a datastructure and return that one datastructure. That could be an array

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

a dictionary

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

Set func = d

a custom object

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

an ArrayList

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

Set func = a

or some other collection.

Note that for returning objects you need to use the Set keyword when assigning the return value of the function:

Set temp = func(a, b)
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
2

Yes, with the use of the Array function you can return multiple values from single function.

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

then call function like:

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.
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
Gimmet
  • 97
  • 7