My little sample code
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
should output 3 but outputs 1. To be more specific the ana
variable is not modified after the call t开发者_Go百科o the AddNr
function.
My environment is Microsoft Visual Basic 6.5 inside Excel 2007.
Remou nailed it already, but I thought the role of parentheses in function calls could be fleshed out a bit. Adding an extra set of parentheses to an argument in a procedure call forces that argument to be passed by value, regardless of whether the called procedure wants the argument by reference or by value. The official help page from Microsoft on this topic is here: How to: Force an Argument to Be Passed by Value (Visual Basic).
The concept is most easily explained by an example:
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
That should be:
AddNr ana
That is, no brackets.
From Microsoft Help:
Remarks
You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.
精彩评论