1. 按值传递参数
按值传递参数时,是将实在参数的值复制一个形式参数中,如果在调用过程中改变了形式参数的值,不会影响实在参数本身,即实在参数保持调用前的值不变。
按值传递参数方法是在形式参数前加上ByVal,如:Sub S1(ByVal a As Integer,ByVal b As integer) ;另外一些特别情况也是按值传递参数,如实在参数是常数、表达式时; 对于实在参数是变量时,只要在其左右加上圆括号,如 Call Sub1((x),(y))。
2.按地址传递参数
按地址传递参数时,把实在参数的地址传送给被调用过程,形式参数和实在参数共用内存的同一地址。在被调用过程中,形式参数的值一旦改变,相应实参的值也跟着改变。
按地址传递参数方法是在形式参数前加上ByRef,或形式参数前为空,如:Sub S1([ByRef] a As Integer,[ByRef] b As integer) ;形参数组只能按地址传递参数。
举例1:
Private Sub Form_Click()
Dim a As Integer, b As Integer
a = 10: b = 25
Call sub1(a, b)
Print a, b
End Sub
Private Sub sub1(ByVal m As Integer, ByVal n As Integer)
Dim temp As Integer
temp = m
m = n
n = temp
Print m, n, temp
End Sub
运行结果是:
在窗体第一行显示:25 10 10
在窗体第二行显示:10 25
见下图:
举例2:
Private Sub Form_Click()
Dim a As Integer, b As Integer
a = 10: b = 25
Call sub1(a, b)
Print a, b
End Sub
Private Sub sub1(ByVal m As Integer, n As Integer)
Dim temp As Integer
temp = m
m = n
n = temp
Print m, n, temp
End Sub
运行结果是:
在窗体第一行显示:25 10 10
在窗体第二行显示:10 10
见下图:
Private Sub Form_Click()
Dim a As Integer, b As Integer
a = 10: b = 25
Call sub1(a, b)
Print a, b
End Sub
Private Sub sub1(m As Integer, ByVal n As Integer)
Dim temp As Integer
temp = m
m = n
n = temp
Print m, n, temp
End Sub
运行结果是:
在窗体第一行显示:25 10 10
在窗体第二行显示:25 25
见下图:
举例4:
Private Sub Form_Click()
Dim a As Integer, b As Integer
a = 10: b = 25
Call sub1(a, b)
Print a, b
End Sub
Private Sub sub1(m As Integer, n As Integer)
Dim temp As Integer
temp = m
m = n
n = temp
Print m, n, temp
End Sub
运行结果是:
在窗体第一行显示:25 10 10
在窗体第二行显示:25 10
见下图:
Private Sub Form_Click()
Dim a As Integer, b As Integer
a = 20: b = 50
p1 a, b
p2 a, b
p3 a, b
Print "a="; a, "b="; b
End Sub
Private Sub p1(x As Integer, ByVal y As Integer)
x = x + 10
y = y + 20
End Sub
Private Sub p2(ByVal x As Integer, y As Integer)
x = x + 10
y = y + 20
End Sub
Private Sub p3(ByVal x As Integer, ByVal y As Integer)
x = x + 10
y = y + 20
End Sub
运行结果是:
在窗体上显示:a= 30 b=70
见下图: