ByRef seems to receive the value and not the reference in VBA 6.0

断了今生、忘了曾经 提交于 2019-12-20 01:46:04

问题


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 to the AddNr function.

My environment is Microsoft Visual Basic 6.5 inside Excel 2007.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/4876524/byref-seems-to-receive-the-value-and-not-the-reference-in-vba-6-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!