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

后端 未结 2 1833
予麋鹿
予麋鹿 2021-01-20 15:20

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
         


        
相关标签:
2条回答
  • 2021-01-20 15:57

    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
    
    0 讨论(0)
  • 2021-01-20 16:05

    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.

    0 讨论(0)
提交回复
热议问题