解决function只能传回一个值的问题
--------------------------------------------------------------------------------
●用function当成子程序的一个好处,就是function本身可以传回一个值到上一层呼叫的子程序里,但问题来了,若为了工作上的需要,想一次传回一个以上的值,那该怎么办?
private sub command1_click()
myreturn 5, 6
end sub
private function myreturn(x, y) as long
a = x + y
b = x - y
c = x * y
d = x / y
'想传回a、b、c、d四个数值回去,怎么写?
end function
●这是一个基本的观念问题,子程序与子程序间的传值有byval与byref两种,byval是两个子程序间的传值放在不同的内存位置,而预设的byref则是将传值放在同一个内存位置上,故这一点可以拿来利用,可将上式改写成:
private sub command1_click()
myreturn 5, 6, ans1, ans2 ,ans3 ,ans4
msgbox "答案分别是" & ans1 & "," & ans2 & "," & ans3 & "," & ans4
end sub
private function myreturn(x, y, a, b, c, d) as long
a = x + y
b = x - y
c = x * y
d = x / y
end function
●或是把资料作成variant型态数组传回:
private sub command1_click()
ans = myreturn(5, 6)
msgbox "答案分别是" & ans(0) & "," & ans(1) & "," & ans(2) & "," & ans(3)
end sub
private function myreturn(x, y) as variant
myreturn = array(x + y, x - y, x * y, x / y)
end function