Rad*_*ana 3 vba pass-by-reference pass-by-value
我的小样本代码
Function AddNr(ByRef x As Integer) As Integer
x = x + 2
AddNr = x
End Function
Sub test()
Dim ana As Integer
ana = 1
AddNr (ana)
MsgBox ana
End Sub
Run Code Online (Sandbox Code Playgroud)
应输出3但输出1.更具体地说,ana在调用AddNr函数后不修改变量.
我的环境是Excel 2007中的Microsoft Visual Basic 6.5.
mwo*_*e02 10
Remou已经把它钉了,但是我认为括号在函数调用中的作用可能会有点充实.在过程调用中向参数添加一组额外的括号会强制该参数按值传递,无论被调用的过程是通过引用还是通过值来获取参数.Microsoft关于此主题的官方帮助页面如下:如何:强制参数通过值传递(Visual Basic).
通过一个例子可以很容易地解释这个概念:
Sub Foo(ByRef Bar)
Bar = 1
End Sub
Sub TestFoo()
Dim Bar
Bar = 0
Foo Bar 'The variable Bar is passed ByRef to Foo
Debug.Print Bar '--> 1
Bar = 0
Foo (Bar) 'The expression (Bar) is evaluated and
' the resultant value 0 is passed ByVal to Foo
Debug.Print Bar '--> 0
Bar = 0
Call Foo(Bar) 'The variable Bar is passed ByRef to Foo
Debug.Print Bar '--> 1
Bar = 0
Call Foo((Bar)) 'The expression (Bar) is evaluated and
' the resultant value 0 is passed ByVal to Foo
Debug.Print Bar '--> 0
End Sub
Run Code Online (Sandbox Code Playgroud)
那应该是:
AddNr ana
Run Code Online (Sandbox Code Playgroud)
也就是说,没有括号.
从Microsoft帮助:
备注
调用过程时,不需要使用Call关键字.但是,如果使用Call关键字调用需要参数的过程,则必须将参数列表括在括号中.如果省略Call关键字,则还必须省略argumentlist周围的括号.如果使用Call语法调用任何内部函数或用户定义函数,则会丢弃函数的返回值.