VBA中方法传参
将变量做为参数传递给方法
1 Sub Test() 2 Dim a As Integer 3 a = 1 4 Add a 5 Debug.Print a '引用传递,a的值发生了变化,输出101 6 End Sub 7 8 Function Add(a As Integer) 9 a = a + 100 10 End Function
结论:VB传参时默认是引用传递byRef。
使用byVal关键字强制形参为值传递
1 Sub Test() 2 Dim a As Integer 3 a = 1 4 Add a 5 Debug.Print a '值传递,a的值没有变化,输出1 6 End Sub 7 8 Function Add(ByVal a As Integer) 9 a = a + 100 10 End Function
调用一个有返回值函数
1 Sub Test() 2 Dim a As Integer 3 a = 1 4 Dim sum As Integer 5 sum = Add(a) 6 Debug.Print sum '引用传递,输出101 7 End Sub 8 9 Function Add(a As Integer) As Integer 10 Add = a + 100 11 End Function
认识“()”
1 Sub Test() 2 Dim a As Integer 3 a = 1 4 Add (a) 5 Debug.Print a 'a的值没有变化,输出1 6 End Sub 7 8 Function Add(ByRef a As Integer) As Integer 9 a = a + 100 10 End Function
解释:
1、Add只有一个参数,并且是“过程式调用”方式的时候,VBE“偷偷”把代码自动改为了Add (a)。注意,Add和(a)之间有个“空格”
2、()在此有完全不同的意义,可以理解它是一个运算符。(a)生成了一个临时变量,a的一个副本,然后将这个临时变量(a)传递给Add
3、a本身并没有传递给Add方法,所以a的值并不会有任何变化。
将一个数组做为参数传递给方法:
1 Sub Test() 2 Dim arr(2) As Integer 3 arr(0) = 1 4 arr(1) = 2 5 arr(2) = 3 6 7 showArray arr 8 Dim i As Integer 9 For i = 0 To 2 10 Debug.Print arr(i) '输出101,102,103 11 Next i 12 End Sub 13 14 Function showArray(arr() As Integer) 15 Dim i As Integer 16 For i = 0 To 2 17 arr(i) = arr(i) + 100 18 Next i 19 End Function
和()有关的一个常见错误和保留问题:
1 Sub Test() 2 Dim arr(2) As Integer 3 arr(0) = 1 4 arr(1) = 2 5 arr(2) = 3 6 7 showArray (arr) '编译时报错:缺少数组或用户定义类型 8 Dim i As Integer 9 For i = 0 To 2 10 Debug.Print arr(i) 11 Next i 12 End Sub 13 14 Function showArray(arr() As Integer) 15 Dim i As Integer 16 For i = 0 To 2 17 arr(i) = arr(i) + 100 18 Next i 19 End Function
编译报错:缺少数组或用户定义类型,除了()生成了一个临时变量之外,与此有关的原因暂不明。。
如果形参是arr而不是arr()
1 Sub Test() 2 Dim arr(2) As Integer 3 arr(0) = 1 4 arr(1) = 2 5 arr(2) = 3 6 7 showArray (arr) 8 Dim i As Integer 9 For i = 0 To 2 10 Debug.Print arr(i) '输出1,2,3 11 Next i 12 End Sub 13 14 Function showArray(arr) 15 Dim sum As Integer, i As Integer 16 For i = 0 To 2 17 arr(i) = arr(i) + 100 18 Next i 19 End Function