解决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
本文地址:http://com.8s8s.com/it/it43983.htm