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

后端 未结 2 1834
予麋鹿
予麋鹿 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
    

提交回复
热议问题